CKTIS / C++
std::find_if: first predicate match
std::find_if returns the first iterator in [first, last) for which pred(*i) is not false, or last.
Version: C++23
Syntax
template<class InputIterator, class Predicate>
constexpr InputIterator std::find_if(
InputIterator first, InputIterator last, Predicate pred);
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
ForwardIterator std::find_if(ExecutionPolicy&& exec,
ForwardIterator first, ForwardIterator last, Predicate pred);std::find_if(first, last, pred) from <algorithm> returns the first iterator i for which pred(*i) != false; it returns last if no match exists. The no-policy form is constexpr and accepts an input iterator, while the policy form requires a forward iterator. For N elements the predicate is invoked at most N times.
The example seeks the first even number, finds 8 at index 1, and prints 8 1. An empty range returns last without invoking the predicate. Sequential checking stops at the first match; with an execution policy, invocations can occur in another order even though the earliest matching iterator is returned.
pred(*first) must be well-formed and boolean-testable, and the predicate must not apply a non-constant function through its argument. The range must be valid and last must not be dereferenced. Without a policy, a predicate exception propagates. With any standard policy, an uncaught element-operation exception calls std::terminate; temporary-memory failure can throw std::bad_alloc. Predicate side effects are unsuitable for counting calls, especially in parallel.
Examples
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
int main() {
const std::array values{3, 8, 7, 4};
const auto found = std::find_if(values.begin(), values.end(),
[](int value) { return value % 2 == 0; });
std::cout << *found << ' ' << std::distance(values.begin(), found) << '\n';
}
Result
8 1
std::find_if → 8 1