find / find_if / find_if_not
find / find_if / find_if_not (조건 일치 원소 찾기)
범위에서 특정 값 또는 조건을 만족하는 첫 번째 원소를 찾는 알고리즘이에요. <algorithm> 헤더에 있어요.
출처: cppreference
본문
find는 [first, last)에서 value와 같은 첫 원소를, find_if는 술어 p가 참인 첫 원소를, find_if_not은 p가 거짓인 첫 원소를 찾아요.
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value ); // (1)
template< class InputIt, class UnaryPred >
InputIt find_if( InputIt first, InputIt last, UnaryPred p ); // (2)
template< class InputIt, class UnaryPred >
InputIt find_if_not( InputIt first, InputIt last, UnaryPred p ); // (3)
- 반환 값: 찾은 첫 원소를 가리키는 반복자. 없으면
last. find는operator==로,find_if/find_if_not은 술어로 판정해요.- 복잡도: 찾을 때까지 최대
last - first번의 비교.
C++17부터 실행 정책 오버로드가 추가됐어요.
std::vector<int> v{1, 4, 7, 2};
auto it = std::find(v.begin(), v.end(), 7); // 7의 위치
auto it2 = std::find_if(v.begin(), v.end(),
[](int x){ return x > 5; }); // 첫 5 초과 원소
if (it2 != v.end()) { /* 찾음 */ }
"처음 나오는 특정 값/조건 원소"를 하나 찾는 가장 기본적인 탐색 알고리즘이에요.