algorithm_find

algorithm_find (조건을 만족하는 요소 찾기)

std::find는 특정 값과 같은 첫 요소를, std::find_if는 술어를 만족하는 첫 요소를, std::find_if_not은 술어를 만족하지 않는 첫 요소를 찾아요.

출처: cppreference

본문

std::find, std::find_if, std::find_if_not은 소스 범위 [first, last)에서 특정 기준을 만족하는 첫 번째 요소를 가리키는 반복자를 돌려줘요. 그런 요소가 없으면 last를 돌려줘요. <algorithm> 헤더에 정의되어 있어요.

template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );

template< class InputIt, class UnaryPred >
InputIt find_if( InputIt first, InputIt last, UnaryPred p );

template< class InputIt, class UnaryPred >
InputIt find_if_not( InputIt first, InputIt last, UnaryPred q );
  • findoperator==value와 같은 첫 요소를 찾아요.
  • find_if — 술어 p가 참을 반환하는 첫 요소를 찾아요.
  • find_if_not — 술어 q가 거짓을 반환하는 첫 요소를 찾아요.

병렬 실행 정책을 받는 오버로드도 있어요.

복잡도 (Complexity)

최대 std::distance(first, last)번의 p(또는 q, 또는 비교) 적용이 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6};

    auto it = std::find(v.begin(), v.end(), 4);
    if (it != v.end())
        std::cout << "found " << *it << " at index "
                  << std::distance(v.begin(), it) << '\n';

    auto even = std::find_if(v.begin(), v.end(),
                             [](int x) { return x % 2 == 0; });
    std::cout << "first even number is " << *even << '\n';

    auto odd = std::find_if_not(v.begin(), v.end(),
                                [](int x) { return x % 2 == 0; });
    std::cout << "first odd number is " << *odd << '\n';
}

출력:

found 4 at index 3
first even number is 2
first odd number is 1

더 알아보기 (Learn more)

cppreference