Namespaces
Variants

std::ranges:: find, std::ranges:: find_if, std::ranges:: find_if_not

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더에 정의됨 <algorithm>
호출 시그니처
(1)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class T, class Proj = std:: identity >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >

constexpr I find ( I first, S last, const T & value, Proj proj = { } ) ;
(C++20부터)
(C++26 이전까지)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >

constexpr I find ( I first, S last, const T & value, Proj proj = { } ) ;
(C++26부터)
(2)
template < ranges:: input_range R, class T, class Proj = std:: identity >

requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: borrowed_iterator_t < R >

find ( R && r, const T & value, Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < ranges:: input_range R, class Proj = std:: identity ,

class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: borrowed_iterator_t < R >

find ( R && r, const T & value, Proj proj = { } ) ;
(C++26부터)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >

constexpr I find_if ( I first, S last, Pred pred, Proj proj = { } ) ;
(3) (C++20 이후)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirect_unary_predicate
< std :: projected < ranges:: iterator_t < R > , Proj >> Pred >
constexpr ranges:: borrowed_iterator_t < R >

find_if ( R && r, Pred pred, Proj proj = { } ) ;
(4) (C++20 이후)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >

constexpr I find_if_not ( I first, S last, Pred pred, Proj proj = { } ) ;
(5) (C++20 이후)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirect_unary_predicate
< std :: projected < ranges:: iterator_t < R > , Proj >> Pred >
constexpr ranges:: borrowed_iterator_t < R >

find_if_not ( R && r, Pred pred, Proj proj = { } ) ;
(6) (C++20 이후)

범위 [ first , last ) 내에서 특정 조건을 만족하는 첫 번째 요소를 반환합니다:

1) find value 와 동일한 요소를 검색합니다.
3) find_if 는 술어(predicate) pred true 를 반환하는 요소를 검색합니다.
5) find_if_not 술어(predicate) pred false 를 반환하는 요소를 검색합니다.
2,4,6) (1,3,5) 와 동일하지만, r 를 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 검사할 요소들의 범위
value - 요소들과 비교할 값
pred - 투영된 요소들에 적용할 predicate
proj - 요소들에 적용할 projection

반환값

조건을 만족하는 첫 번째 요소에 대한 반복자 또는 해당 요소가 발견되지 않으면 last 와 동일한 반복자.

복잡도

최대 last - first 번의 술어와 프로젝션 적용.

가능한 구현

**참고:** 제공된 HTML 코드 블록 내에는 번역이 필요한 일반 텍스트가 포함되어 있지 않습니다. 모든 내용이 C++ 코드, HTML 태그, 속성 및 C++ 관련 용어로 구성되어 있어, 지정된 지침에 따라 번역 작업이 필요하지 않습니다.
find (1)
struct find_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             class T = std::projected_value_t<I, Proj>>
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
    constexpr I operator()(I first, S last, const T& value, Proj proj = {}) const
    {
        for (; first != last; ++first)
            if (std::invoke(proj, *first) == value)
                return first;
        return first;
    }
    template<ranges::input_range R, class T, class Proj = std::identity>
    requires std::indirect_binary_predicate<ranges::equal_to,
                 std::projected<ranges::iterator_t<R>, Proj>, const T*>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, const T& value, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(proj));
    }
};
inline constexpr find_fn find;
find_if (3)
struct find_if_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr I operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        for (; first != last; ++first)
            if (std::invoke(pred, std::invoke(proj, *first)))
                return first;
        return first;
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_unary_predicate
                 <std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
    }
};
inline constexpr find_if_fn find_if;
find_if_not (5)
struct find_if_not_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr I operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        for (; first != last; ++first)
            if (!std::invoke(pred, std::invoke(proj, *first)))
                return first;
        return first;
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_unary_predicate
                 <std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
    }
};
inline constexpr find_if_not_fn find_if_not;

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_algorithm_default_value_type 202403 (C++26) 목록 초기화 for algorithms ( 1,2 )

예제

#include <algorithm>
#include <cassert>
#include <complex>
#include <format>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void projector_example()
{
    struct folk_info
    {
        unsigned uid;
        std::string name, position;
    };
    std::vector<folk_info> folks
    {
        {0, "아나", "dev"},
        {1, "밥", "데브옵스"},
        {2, "이브", "ops"}
    };
    const auto who{"이브"};
    if (auto it = std::ranges::find(folks, who, &folk_info::name); it != folks.end())
        std::cout << std::format("프로필:\n"
                                 "    UID: {}\n"
                                 "    이름: {}\n"
                                 "    위치: {}\n\n",
                                 it->uid, it->name, it->position);
}
int main()
{
    namespace ranges = std::ranges;
    projector_example();
    const int n1 = 3;
    const int n2 = 5;
    const auto v = {4, 1, 3, 2};
    if (ranges::find(v, n1) != v.end())
        std::cout << "v contains: " << n1 << '\n';
    else
        std::cout << "v does not contain: " << n1 << '\n';
    if (ranges::find(v.begin(), v.end(), n2) != v.end())
        std::cout << "v contains: " << n2 << '\n';
    else
        std::cout << "v does not contain: " << n2 << '\n';
    auto is_even = [](int x) { return x % 2 == 0; };
    if (auto result = ranges::find_if(v.begin(), v.end(), is_even); result != v.end())
        std::cout << "v에서 첫 번째 짝수 요소: " << *result << '\n';
    else
        std::cout << "v에 짝수 요소가 없습니다\n";
    if (auto result = ranges::find_if_not(v, is_even); result != v.end())
        std::cout << "v에서 첫 번째 홀수 요소: " << *result << '\n';
    else
        std::cout << "v에 홀수 요소가 없습니다\n";
    auto divides_13 = [](int x) { return x % 13 == 0; };
    if (auto result = ranges::find_if(v, divides_13); result != v.end())
        std::cout << "v에서 13으로 나누어지는 첫 번째 요소: " << *result << '\n';
    else
        std::cout << "v의 어떤 요소도 13으로 나누어 떨어지지 않습니다\n";
    if (auto result = ranges::find_if_not(v.begin(), v.end(), divides_13);
        result != v.end())
        std::cout << "v에서 13으로 나누어지지 않는 첫 번째 요소: " << *result << '\n';
    else
        std::cout << "v의 모든 요소가 13으로 나누어 떨어집니다\n";
    std::vector<std::complex<double>> nums{{4, 2}};
    #ifdef __cpp_lib_algorithm_default_value_type
        // T가 (2)에서 추론되어 목록 초기화가 가능해짐
        const auto it = ranges::find(nums, {4, 2});
    #else
        const auto it = ranges::find(nums, std::complex<double>{4, 2});
    #endif
    assert(it == nums.begin());
}

출력:

프로필:
    UID: 2
    이름: Eve
    직책: ops
v에 포함된 요소: 3
v에 포함되지 않은 요소: 5
v의 첫 번째 짝수 요소: 4
v의 첫 번째 홀수 요소: 1
v의 요소 중 13으로 나누어 떨어지는 요소가 없음
v의 13으로 나누어 떨어지지 않는 첫 번째 요소: 4

참고 항목

서로 인접한 두 요소가 같거나(또는 주어진 조건자를 만족하는) 첫 번째 쌍을 찾음
(알고리즘 함수 객체)
특정 범위에서 마지막으로 나타나는 요소 시퀀스를 찾음
(알고리즘 함수 객체)
요소 집합 중 하나를 검색함
(알고리즘 함수 객체)
두 범위가 처음으로 달라지는 위치를 찾음
(알고리즘 함수 객체)
요소 범위의 첫 번째 발생을 검색함
(알고리즘 함수 객체)
특정 기준을 만족하는 첫 번째 요소를 찾음
(함수 템플릿)