std::find() algorithm
- since C++20
- since C++17
- until C++17
// (1)
template< class InputIt, class T >
constexpr InputIt find( InputIt first, InputIt last, const T& value );
// (2)
template< class ExecutionPolicy, class ForwardIt, class T >
ForwardIt find( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, const T& value );
// (1)
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
// (2)
template< class ExecutionPolicy, class ForwardIt, class T >
ForwardIt find( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, const T& value );
// (1)
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
Returns an iterator to the first element in the range satisfiying specific criteria (or last
iterator if there is no such iterator):
-
(1) Searches for an element equal to
value
(usingoperator==
). -
(2) Same as (1), but executed according to
policy
.Overload ResolutionThese overloads participate in overload resolution only if
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(until C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(since C++20) istrue
.
Parameters
first last | The range of elements to apply the function to. |
value | Value to compare the elements to. |
policy | The execution policy to use. See execution policy for details. |
Type requirements
InputIt | LegacyInputIterator |
ForwardIt | LegacyForwardIterator |
Return value
The first iterator it in the range [first
, last
) for which *it == value
is true
.
Complexity
Given N
as std::distance(first, last)
:
At most N comparisons with value
using operator==
.
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 otherExecutionPolicy
, the behavior is implementation-defined. - If the algorithm fails to allocate memory,
std::bad_alloc
is thrown.
Possible implementation
find (1)
template<class InputIt, class T>
constexpr InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first)
if (*first == value)
return first;
return last;
}
Examples
#include <algorithm>
#include <array>
#include <iostream>
int main()
{
const auto v = {1, 2, 3, 4};
for (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 (auto const& 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";
}
v contains 3
v does not contain 5
w contains an even number 4
w does not contain even numbers
Hover to see the original license.