C++ - find_if() 함수와 end() 함수
1. find_if() 함수
template<class InputIt, class UnaryPredicate>
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first) {
if (p(*first)) {
return first;
}
}
return last;
}
algorithm 헤더에 정의
Defined in header "algorithm"
first : 컨테이너의 시작요소
last : 컨테이너의 마지막요소
p : bool 타입의 조건문
[first,last] 범위안의 조건(p)을 만족하는 첫번째 요소를 return
2. find_if() return value
조건을 만족하는 첫 번째 요소 first 를 return
해당 요소가없는 경우 마지막 last 를 return
- find_if 조건문 이후 컨테이너의 end() 함수와 비교하여 요소를 찾았는지를 비교하는 경우가 있음
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
// Create a list of integers with a few initial elements.
vector<int> number_list;
number_list.push_back(10);
number_list.push_back(23);
number_list.push_back(30);
number_list.push_back(45);
number_list.push_back(50);
// Use the find_if function and a lambda expression to find the
// first even number in the vector list.
const vector<int>::const_iterator result =
find_if(number_list.begin(), number_list.end(),[](int n) { return (n % 2) == 0; });
// Print the result.
if (result != number_list.end()) { //if find_if returns last value, nothing has been found in container
cout << "The first even number in the list is " << *result << "." << endl;
} else {
cout << "The list contains no even number_list." << endl;
}
}
OutPut:
The first even number in the list is 10
- if (result != number_list.end()) : number_list 내의 컨테이너에서 number_list.end()를 return하면 컨테이너내에서 조건에 맞는 요소를 찾지 못한경우를 의미