Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::any_of: whether a matching element exists

std::any_of returns true when a predicate is true for at least one element. An empty range always produces false.

Version: C++23

Syntax

template<class InputIt, class UnaryPred>
constexpr bool any_of(InputIt first, InputIt last, UnaryPred predicate);

template<class ExecutionPolicy, class ForwardIt, class UnaryPred>
bool any_of(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPred predicate);

std::any_of from <algorithm> tests [first, last) with a unary predicate. The sequential overload may stop at the first true; when nothing matches it returns false. For an empty range the predicate is never invoked.

The function expresses an existence query without a manual loop. In the worst case it calls the predicate for every element. The predicate must not modify the element or depend on a particular call count.

Execution-policy overloads may change ordering and invoke calls concurrently. Side effects must therefore be safe, and with any standard execution policy, including std::execution::seq, an uncaught predicate exception causes std::terminate.

Examples

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

int main() {
    const std::array values{1, 3, 6};
    const bool hasEven = std::any_of(values.begin(), values.end(), [](int value) {
        return value % 2 == 0;
    });
    std::cout << hasEven << '\n';
}

Result

1

std::any_of → 1

Sources