Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/find"

From cppreference.com
< cpp‎ | algorithm
(Return value update.)
m (FTM.)
 
(26 intermediate revisions by 7 users not shown)
Line 3: Line 3:
 
{{dcl begin}}
 
{{dcl begin}}
 
{{dcl header|algorithm}}
 
{{dcl header|algorithm}}
{{dcl rev multi|num=1|dcl1=
+
{{dcl rev begin|num=1}}
 +
{{dcla|anchor=1|constexpr=c++20|until=c++26|
 
template< class InputIt, class T >
 
template< class InputIt, class T >
 
InputIt find( InputIt first, InputIt last, const T& value );
 
InputIt find( InputIt first, InputIt last, const T& value );
| since2=c++20|dcl2=
+
}}
template< class InputIt, class T >
+
{{dcl|since=c++26|1=
 +
template< class InputIt, class T = typename std::iterator_traits
 +
                                      <InputIt>::value_type >
 
constexpr InputIt find( InputIt first, InputIt last, const T& value );
 
constexpr InputIt find( InputIt first, InputIt last, const T& value );
 
}}
 
}}
{{dcl|num=2|since=c++17|
+
{{dcl rev end}}
 +
{{dcl rev begin|num=2}}
 +
{{dcl|since=c++17|until=c++26|
 
template< class ExecutionPolicy, class ForwardIt, class T >
 
template< class ExecutionPolicy, class ForwardIt, class T >
 
ForwardIt find( ExecutionPolicy&& policy,
 
ForwardIt find( ExecutionPolicy&& policy,
 
                 ForwardIt first, ForwardIt last, const T& value );
 
                 ForwardIt first, ForwardIt last, const T& value );
 
}}
 
}}
{{dcl rev multi|num=3|dcl1=
+
{{dcl|since=c++26|1=
template< class InputIt, class UnaryPredicate >
+
template< class ExecutionPolicy,
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
+
          class ForwardIt, class T = typename std::iterator_traits
|since2=c++20|dcl2=
+
                                        <ForwardIt>::value_type >
template< class InputIt, class UnaryPredicate >
+
ForwardIt find( ExecutionPolicy&& policy,
constexpr InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
+
                ForwardIt first, ForwardIt last, const T& value );
 +
}}
 +
{{dcl rev end}}
 +
{{dcla|num=3|constexpr=c++20|
 +
template< class InputIt, class UnaryPred >
 +
InputIt find_if( InputIt first, InputIt last, UnaryPred p );
 
}}
 
}}
 
{{dcl|num=4|since=c++17|
 
{{dcl|num=4|since=c++17|
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
+
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >
 
ForwardIt find_if( ExecutionPolicy&& policy,
 
ForwardIt find_if( ExecutionPolicy&& policy,
                   ForwardIt first, ForwardIt last, UnaryPredicate p );
+
                   ForwardIt first, ForwardIt last, UnaryPred p );
 
}}
 
}}
{{dcl rev multi|num=5
+
{{dcla|num=5|since=c++11|constexpr=c++20|
|since1=c++11|dcl1=
+
template< class InputIt, class UnaryPred >
template< class InputIt, class UnaryPredicate >
+
InputIt find_if_not( InputIt first, InputIt last, UnaryPred q );
InputIt find_if_not( InputIt first, InputIt last, UnaryPredicate q );
+
|since2=c++20|dcl2=
+
template< class InputIt, class UnaryPredicate >
+
constexpr InputIt find_if_not( InputIt first, InputIt last, UnaryPredicate q );
+
 
}}
 
}}
 
{{dcl|num=6|since=c++17|
 
{{dcl|num=6|since=c++17|
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
+
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >
 
ForwardIt find_if_not( ExecutionPolicy&& policy,
 
ForwardIt find_if_not( ExecutionPolicy&& policy,
                       ForwardIt first, ForwardIt last, UnaryPredicate q );
+
                       ForwardIt first, ForwardIt last, UnaryPred q );
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
  
Returns the first iterator {{c|it}} in the [[cpp/iterator#Ranges|range]] {{tt|[first, last)}} that satisfies specific criteria:
+
Returns an iterator to the first element in the range {{range|first|last}} that satisfies specific criteria (or {{c|last}} if there is no such iterator).
@1@ {{c|1=*it == value}} is {{c|true}}
+
  
@3@ {{c|1=p(*it) != false}} is {{c|true}}
+
@1@ {{tt|find}} searches for an element equal to {{c|value}} (using {{tt|1=operator==}}).
 +
 
 +
@3@ {{tt|find_if}} searches for an element for which predicate {{c|p}} returns {{c|true}}.
 +
 
 +
@5@ {{tt|find_if_not}} searches for an element for which predicate {{c|q}} returns {{c|false}}.
 +
 
 +
@2,4,6@ Same as {{v|1,3,5}}, but executed according to {{c|policy}}.
 +
@@ {{cpp/algorithm/parallel overload precondition|plural=yes}}
  
@5@ {{c|1=q(*it) == false}} is {{c|true}}
 
@2,4,6@ Same as {{v|1,3,5}}, but executed according to {{c|policy}}. {{cpp/algorithm/parallel overload precondition|plural=true}}
 
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
Line 63: Line 73:
  
 
===Return value===
 
===Return value===
The first iterator satisfying the condition or {{c|last}} if there is no such iterator.
+
The first iterator {{c|it}} in the [[cpp/iterator#Ranges|range]] {{range|first|last}} satisfying the following condition or {{c|last}} if there is no such iterator:
 +
@1,2@ {{c|1=*it == value}} is {{c|true}}.
 +
@3,4@ {{c|1=p(*it)}} is {{c|true}}.
 +
@5,6@ {{c|1=q(*it)}} is {{c|false}}.
  
 
===Complexity===
 
===Complexity===
At most {{tt|N}} applications of the predicate, where {{c|1= N = std::distance(first, last)}}.
+
Given {{mathjax-or|\(\scriptsize N\)|N}} as {{c|std::distance(first, last)}}:
 +
@1,2@ At most {{mathjax-or|\(\scriptsize N\)|N}} comparisons with {{c|value}} using {{tt|1=operator==}}.
 +
@3,4@ At most {{mathjax-or|\(\scriptsize N\)|N}} applications of the predicate {{c|p}}.
 +
@5,6@ At most {{mathjax-or|\(\scriptsize N\)|N}} applications of the predicate {{c|q}}.
  
 
===Exceptions===
 
===Exceptions===
Line 73: Line 89:
 
===Possible implementation===
 
===Possible implementation===
 
{{eq impl
 
{{eq impl
|1=
+
|title1=find|ver1=1|1=
template<class InputIt, class T>
+
template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
 
constexpr InputIt find(InputIt first, InputIt last, const T& value)
 
constexpr InputIt find(InputIt first, InputIt last, const T& value)
 
{
 
{
Line 83: Line 99:
 
     return last;
 
     return last;
 
}
 
}
|title2=Third version|2=
+
|title2=find_if|ver2=3|2=
template<class InputIt, class UnaryPredicate>
+
template<class InputIt, class UnaryPred>
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
+
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPred p)
 
{
 
{
 
     for (; first != last; ++first)
 
     for (; first != last; ++first)
Line 93: Line 109:
 
     return last;
 
     return last;
 
}
 
}
|title3=Fifth version|3=
+
|title3=find_if_not|ver3=5|3=
template<class InputIt, class UnaryPredicate>
+
template<class InputIt, class UnaryPred>
constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q)
+
constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPred q)
 
{
 
{
 
     for (; first != last; ++first)
 
     for (; first != last; ++first)
Line 106: Line 122:
  
 
===Notes===
 
===Notes===
If you do not have C++11, an equivalent to {{tt|std::find_if_not}} is to use {{tt|std::find_if}} with the negated predicate.
+
If C++11 is not available, an equivalent to {{tt|std::find_if_not}} is to use {{tt|std::find_if}} with the negated predicate.
{{eq fun | 1=
+
{{eq fun|1=
template<class InputIt, class UnaryPredicate>
+
template<class InputIt, class UnaryPred>
InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q)
+
InputIt find_if_not(InputIt first, InputIt last, UnaryPred q)
 
{
 
{
 
     return std::find_if(first, last, std::not1(q));
 
     return std::find_if(first, last, std::not1(q));
 
}
 
}
 
}}
 
}}
 +
 +
{{feature test macro|__cpp_lib_algorithm_default_value_type|value=202403|std=C++26|[[cpp/language/list initialization|List-initialization]] for algorithms {{vl|1,2}}}}
  
 
===Example===
 
===Example===
 
{{example
 
{{example
|The following example finds integers in given vector.
+
|The following example finds numbers in given sequences.
 
|code=
 
|code=
#include <iostream>
 
 
#include <algorithm>
 
#include <algorithm>
 +
#include <array>
 +
#include <cassert>
 +
#include <complex>
 +
#include <iostream>
 
#include <vector>
 
#include <vector>
#include <iterator>
 
  
 
int main()
 
int main()
 
{
 
{
     std::vector<int> v{1, 2, 3, 4};
+
     const auto v = {1, 2, 3, 4};
    int n1 = 3;
+
 
     int n2 = 5;
+
     for (const int n : {3, 5})
    auto is_even = [](int i){ return i%2 == 0; };
+
        (std::find(v.begin(), v.end(), n) == std::end(v))
   
+
            ? std::cout << "v does not contain " << n << '\n'
    auto result1 = std::find(begin(v), end(v), n1);
+
            : std::cout << "v contains " << n << '\n';
    auto result2 = std::find(begin(v), end(v), n2);
+
 
    auto result3 = std::find_if(begin(v), end(v), is_even);
+
     auto is_even = [](int i) { return i % 2 == 0; };
   
+
 
    (result1 != std::end(v))
+
     for (const auto& w : {std::array{3, 1, 4}, {1, 3, 5}<!---->})
        ? std::cout << "v contains " << n1 << '\n'
+
        if (auto it = std::find_if(begin(w), end(w), is_even); it != std::end(w))
        : std::cout << "v does not contain " << n1 << '\n';
+
            std::cout << "w contains an even number " << *it << '\n';
      
+
         else
     (result2 != std::end(v))
+
            std::cout << "w does not contain even numbers\n";
        ? std::cout << "v contains " << n2 << '\n'
+
 
         : std::cout << "v does not contain " << n2 << '\n';
+
    std::vector<std::complex<double>> nums{<!---->{4, 2}<!---->};
      
+
     #ifdef __cpp_lib_algorithm_default_value_type
    (result3 != std::end(v))
+
        // T gets deduced making list-initialization possible
         ? std::cout << "v contains an even number: " << *result3 << '\n'
+
        const auto it = std::find(nums.begin(), nums.end(), {4, 2});
        : std::cout << "v does not contain even numbers\n";
+
    #else
 +
         const auto it = std::find(nums.begin(), nums.end(), std::complex<double>{4, 2});
 +
    #endif
 +
    assert(it == nums.begin());  
 
}
 
}
 
|output=
 
|output=
 
v contains 3
 
v contains 3
 
v does not contain 5
 
v does not contain 5
v contains an even number: 2
+
w contains an even number 4
 +
w does not contain even numbers
 
}}
 
}}
  
 
===Defect reports===
 
===Defect reports===
 
{{dr list begin}}
 
{{dr list begin}}
{{dr list item|wg=lwg|dr=283|std=C++98|before={{tt|T}} was required to be {{named req|EqualityComparable}}, but the value type of {{tt|InputIt}} is not always {{tt|T}}|after=removed the requirement}}
+
{{dr list item|wg=lwg|dr=283|std=C++98|before={{tt|T}} was required to be {{named req|EqualityComparable}}, but<br>the value type of {{tt|InputIt}} might not be {{tt|T}}|after=removed the requirement}}
 
{{dr list end}}
 
{{dr list end}}
  

Latest revision as of 21:13, 20 May 2024

 
 
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
(C++11)                (C++11)(C++11)

findfind_iffind_if_not
(C++11)
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
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
 
Defined in header <algorithm>
(1)
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
(constexpr since C++20)
(until C++26)
template< class InputIt, class T = typename std::iterator_traits

                                       <InputIt>::value_type >

constexpr InputIt find( InputIt first, InputIt last, const T& value );
(since C++26)
(2)
template< class ExecutionPolicy, class ForwardIt, class T >

ForwardIt find( ExecutionPolicy&& policy,

                ForwardIt first, ForwardIt last, const T& value );
(since C++17)
(until C++26)
template< class ExecutionPolicy,

          class ForwardIt, class T = typename std::iterator_traits
                                         <ForwardIt>::value_type >
ForwardIt find( ExecutionPolicy&& policy,

                ForwardIt first, ForwardIt last, const T& value );
(since C++26)
template< class InputIt, class UnaryPred >
InputIt find_if( InputIt first, InputIt last, UnaryPred p );
(3) (constexpr since C++20)
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >

ForwardIt find_if( ExecutionPolicy&& policy,

                   ForwardIt first, ForwardIt last, UnaryPred p );
(4) (since C++17)
template< class InputIt, class UnaryPred >
InputIt find_if_not( InputIt first, InputIt last, UnaryPred q );
(5) (since C++11)
(constexpr since C++20)
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >

ForwardIt find_if_not( ExecutionPolicy&& policy,

                       ForwardIt first, ForwardIt last, UnaryPred q );
(6) (since C++17)

Returns an iterator to the first element in the range [firstlast) that satisfies specific criteria (or last if there is no such iterator).

1) find searches for an element equal to value (using operator==).
3) find_if searches for an element for which predicate p returns true.
5) find_if_not searches for an element for which predicate q returns false.
2,4,6) Same as (1,3,5), but executed according to policy.
These overloads participate in overload resolution only if

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.

(until C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.

(since C++20)

Contents

[edit] Parameters

first, last - the range of elements to examine
value - value to compare the elements to
policy - the execution policy to use. See execution policy for details.
p - unary predicate which returns ​true for the required element.

The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy(since C++11). ​

q - unary predicate which returns ​false for the required element.

The expression q(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy(since C++11). ​

Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.
-
ForwardIt must meet the requirements of LegacyForwardIterator.
-
UnaryPredicate must meet the requirements of Predicate.

[edit] Return value

The first iterator it in the range [firstlast) satisfying the following condition or last if there is no such iterator:

1,2) *it == value is true.
3,4) p(*it) is true.
5,6) q(*it) is false.

[edit] Complexity

Given N as std::distance(first, last):

1,2) At most N comparisons with value using operator==.
3,4) At most N applications of the predicate p.
5,6) At most N applications of the predicate q.

[edit] Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

[edit] Possible implementation

find
template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
constexpr InputIt find(InputIt first, InputIt last, const T& value)
{
    for (; first != last; ++first)
        if (*first == value)
            return first;
 
    return last;
}
find_if
template<class InputIt, class UnaryPred>
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPred p)
{
    for (; first != last; ++first)
        if (p(*first))
            return first;
 
    return last;
}
find_if_not
template<class InputIt, class UnaryPred>
constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPred q)
{
    for (; first != last; ++first)
        if (!q(*first))
            return first;
 
    return last;
}

[edit] Notes

If C++11 is not available, an equivalent to std::find_if_not is to use std::find_if with the negated predicate.

template<class InputIt, class UnaryPred>
InputIt find_if_not(InputIt first, InputIt last, UnaryPred q)
{
    return std::find_if(first, last, std::not1(q));
}
Feature-test macro Value Std Feature
__cpp_lib_algorithm_default_value_type 202403 (C++26) List-initialization for algorithms (1,2)

[edit] Example

The following example finds numbers in given sequences.

#include <algorithm>
#include <array>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
 
int main()
{
    const auto v = {1, 2, 3, 4};
 
    for (const int n : {3, 5})
        (std::find(v.begin(), v.end(), n) == std::end(v))
            ? std::cout << "v does not contain " << n << '\n'
            : std::cout << "v contains " << n << '\n';
 
    auto is_even = [](int i) { return i % 2 == 0; };
 
    for (const auto& w : {std::array{3, 1, 4}, {1, 3, 5}})
        if (auto it = std::find_if(begin(w), end(w), is_even); it != std::end(w))
            std::cout << "w contains an even number " << *it << '\n';
        else
            std::cout << "w does not contain even numbers\n";
 
    std::vector<std::complex<double>> nums{{4, 2}};
    #ifdef __cpp_lib_algorithm_default_value_type
        // T gets deduced making list-initialization possible
        const auto it = std::find(nums.begin(), nums.end(), {4, 2});
    #else
        const auto it = std::find(nums.begin(), nums.end(), std::complex<double>{4, 2});
    #endif
    assert(it == nums.begin());   
}

Output:

v contains 3
v does not contain 5
w contains an even number 4
w does not contain even numbers

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 283 C++98 T was required to be EqualityComparable, but
the value type of InputIt might not be T
removed the requirement

[edit] See also

finds the first two adjacent items that are equal (or satisfy a given predicate)
(function template) [edit]
finds the last sequence of elements in a certain range
(function template) [edit]
searches for any one of a set of elements
(function template) [edit]
finds the first position where two ranges differ
(function template) [edit]
searches for the first occurrence of a range of elements
(function template) [edit]
finds the first element satisfying specific criteria
(niebloid)[edit]