Namespaces
Variants

std::find_first_of

cppreference.net에서
 
 
알고리즘 라이브러리
제약된 알고리즘 및 범위에 대한 알고리즘 (C++20)
제약된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 검색 연산
(분할된 범위에서)
집합 연산 (정렬된 범위에서)
병합 연산 (정렬된 범위에서)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
헤더 <algorithm>
template< class InputIt, class ForwardIt >
InputIt find_first_of( InputIt first1, InputIt last1,
                       ForwardIt first2, ForwardIt last2 );
에 정의됨 (1) (C++20부터 constexpr)
template< class InputIt, class ForwardIt, class BinaryPred >
InputIt find_first_of( InputIt first1, InputIt last1,
                       ForwardIt first2, ForwardIt last2,
                       BinaryPred p );
(2) (C++20부터 constexpr)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt1 find_first_of( ExecutionPolicy&& policy,
                          ForwardIt1 first1, ForwardIt1 last1,
                          ForwardIt2 first2, ForwardIt2 last2 );
(3) (C++17부터)
template< class ExecutionPolicy,
          class ForwardIt1, class ForwardIt2, class BinaryPred >
ForwardIt1 find_first_of( ExecutionPolicy&& policy,
                          ForwardIt1 first1, ForwardIt last1,
                          ForwardIt2 first2, ForwardIt2 last2,
                          BinaryPred p );
(4) (C++17부터)

원본 범위 [first1, last1) 에서 대상 범위 [first2, last2) 의 요소 중 첫 번째 것을 검색합니다.

1) 요소 비교는 operator== 을 사용하여 수행됩니다.
2) 요소 비교는 주어진 이항 술어 p 을 사용하여 수행됩니다.
3,4) (1,2) 와 동일하지만 policy 에 따라 실행됩니다.
이러한 오버로드는 다음 표현식의 값이 true 인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)

매개변수

first1, last1 - 소스 범위
를 정의하는 반복자 쌍first2, last2 - 대상 범위
를 정의하는 반복자 쌍p - 요소가 같음으로 처리되어야 하는 경우 ​true 을 반환하는 이항 술어.

술어 함수의 시그니처는 다음과 동등해야 합니다:

bool pred(const Type1 &a, const Type2 &b);

시그니처에 const &가 있을 필요는 없지만, 함수는 전달된 객체를 수정해서는 안 되며, Type1 및 Type2 유형의 모든 값((const)일 수 있음)을 값 카테고리에 관계없이 받아들일 수 있어야 합니다. (따라서 Type1 &는 허용되지 않으며, Type1도 허용되지 않습니다. 단, Type1 이동이 복사와 동등한 경우(C++11 이후)는 예외입니다).
Type1 및 Type2 유형은 ForwardIt1 및 ForwardIt2 유형의 객체를 역참조한 후 각각 Type1 및 Type2로 암시적으로 변환될 수 있어야 합니다. ​

policy - 사용할 실행 정책
유형 요구 사항
-
InputIt는 LegacyInputIterator의 요구 사항을 충족해야 합니다.
-
ForwardIt는 LegacyForwardIterator의 요구 사항을 충족해야 합니다.
-
ForwardIt1는 LegacyForwardIterator의 요구 사항을 충족해야 합니다.
-
ForwardIt2는 LegacyForwardIterator의 요구 사항을 충족해야 합니다.
-
BinaryPred는 BinaryPredicate의 요구 사항을 충족해야 합니다.

반환값

소스 범위에서 대상 범위의 요소와 일치하는 첫 번째 요소를 가리키는 반복자입니다.

대상 범위가 비어 있거나 그러한 요소가 발견되지 않으면 last1이(가) 반환됩니다.

복잡도

주어진 N1 로 std::distance(first1, last1) 및 N2 로 std::distance(first2, last2):

1) 최대 N1⋅2 번의 비교 (는) operator==.
2) 최대 N1⋅2 번의 적용 (은) p.
3) 𝓞(N1⋅2) 번의 비교 (는) operator==.
4) 𝓞(N1⋅2) 번의 적용 (은) p.

예외

3,4) 실행 과정 중:
  • 병렬화에 필요한 임시 메모리 자원을 사용할 수 없는 경우, std::bad_alloc이 발생합니다.
  • 알고리즘 인수를 통해 객체에 접근하는 도중 처리되지 않은 예외가 발생하면, 동작은 실행 정책에 따라 결정됩니다(표준 정책의 경우 표준 정책, std::terminate가 호출됩니다).

가능한 구현

find_first_of (1)
template<class InputIt, class ForwardIt>
InputIt find_first_of(InputIt first1, InputIt last1,
                      ForwardIt first2, ForwardIt last2)
{
    for (; first1 != last1; ++first1)
        for (ForwardIt it = first2; it != last2; ++it)
            if (*first1 == *it)
                return first1;
    return last1;
}
find_first_of (2)
template<class InputIt, class ForwardIt, class BinaryPred>
InputIt find_first_of(InputIt first1, InputIt last1,
                      ForwardIt first2, ForwardIt last2,
                      BinaryPred p)
{
    for (; first1 != last1; ++first1)
        for (ForwardIt it = first2; it != last2; ++it)
            if (p(*first1, *it))
                return first1;
    return last1;
}

예제

다음 코드는 정수 벡터에서 지정된 정수 중 하나를 검색합니다:

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

auto print_sequence = [](const auto id, const auto& seq, int pos = -1)
{
    std::cout << id << "{ ";
    for (int i{}; const auto& e : seq)
    {
        const bool mark{i == pos};
        std::cout << (i++ ? ", " : "");
        std::cout << (mark ? "[ " : "") << e << (mark ? " ]" : "");
    }
    std::cout << " }\n";
};

int main()
{
    const std::vector<int> v{0, 2, 3, 25, 5};
    const auto t1 = {19, 10, 3, 4};
    const auto t2 = {1, 6, 7, 9};
    
    auto find_any_of = [](const auto& v, const auto& t)
    {
        const auto result = std::find_first_of(v.begin(), v.end(),
                                               t.begin(), t.end());
        if (result == v.end())
        {
            std::cout << "No elements of v are equal to any element of ";
            print_sequence("t = ", t);
            print_sequence("v = ", v);
        }
        else
        {
            const auto pos = std::distance(v.begin(), result);
            std::cout << "Found a match (" << *result << ") at position " << pos;
            print_sequence(", where t = ", t);
            print_sequence("v = ", v, pos);
        }
    };
    
    find_any_of(v, t1);
    find_any_of(v, t2);
}

출력:

Found a match (3) at position 2, where t = { 19, 10, 3, 4 }
v = { 0, 2, [ 3 ], 25, 5 }
No elements of v are equal to any element of t = { 1, 6, 7, 9 }
v = { 0, 2, 3, 25, 5 }

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 발표된 동작 올바른 동작
LWG 576 C++98 first1 및 last1는 LegacyForwardIterator이어야 했습니다. 그들은 LegacyInputIterator만 있으면 됩니다.
LWG 1205 C++98 대상 범위가 비어 있는 경우 반환 값이 불분명했습니다. 이 경우 last1를 반환합니다.

참고 항목

요소 집합 중 하나를 검색합니다
(알고리즘 함수 객체)
특정 기준을 충족하는 첫 번째 요소를 찾습니다
(함수 템플릿 & 알고리즘 함수 객체)