Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::find_if_not: first element failing a condition

std::find_if_not returns the first iterator in [first, last) for which pred(*i) is false, or last.

Version: C++23

Syntax

template<class InputIterator, class Predicate>
constexpr InputIterator std::find_if_not(
    InputIterator first, InputIterator last, Predicate pred);

template<class ExecutionPolicy, class ForwardIterator, class Predicate>
ForwardIterator std::find_if_not(ExecutionPolicy&& exec,
    ForwardIterator first, ForwardIterator last, Predicate pred);

std::find_if_not(first, last, pred) from <algorithm> returns the first iterator i for which pred(*i) == false; if every element satisfies the condition, it returns last. The no-policy overload is constexpr and needs only an input iterator, while the policy overload requires a forward iterator. Complexity is at most N predicate invocations.

The example uses “is even” and finds the first value that fails it: 7 at index 2, so it prints 7 2. An empty range and a range whose every element satisfies the predicate both yield last; the result must be checked before dereferencing.

The predicate must produce a boolean-testable result and must not modify an element through its argument. With an execution policy, evaluations can occur out of order, so their side effects are not a sequencing mechanism. Without a policy, a predicate exception propagates. With any standard policy, an uncaught element-operation exception leads to std::terminate, while temporary-memory failure can throw std::bad_alloc.

Examples

#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>

int main() {
    const std::array values{2, 8, 7, 4};
    const auto found = std::find_if_not(values.begin(), values.end(),
                                        [](int value) { return value % 2 == 0; });
    std::cout << *found << ' ' << std::distance(values.begin(), found) << '\n';
}

Result

7 2

std::find_if_not → 7 2

Sources