C++ Reference ยท Algorithms
The std::all_of, any_of and none_of algorithms
Reference for C++ std::all_of, std::any_of and std::none_of: test a predicate over a range, short-circuiting, empty-range results and ranges versions.
These three algorithms answer yes/no questions about a whole range. std::all_of is true if the predicate holds for every element, std::any_of is true if it holds for at least one, and std::none_of is true if it holds for none. They stop as soon as the answer is known.
They make intent clear: any_of reads better than a loop with a flag, and unlike std::count it does not keep scanning after the first hit. C++23 adds std::ranges::contains and contains_subrange for the common "is this value in the range?" question.
bool ok = std::all_of(v.begin(), v.end(), [](int x) { return x > 0; });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
template<class InputIt, class Pred> bool all_of(InputIt first, InputIt last, Pred pred); template<class InputIt, class Pred> bool any_of(InputIt first, InputIt last, Pred pred); template<class InputIt, class Pred> bool none_of(InputIt first, InputIt last, Pred pred);
| Name | Description |
|---|---|
first, last |
The half-open range [first, last) to test. |
pred |
Called with each element; returns something convertible to bool. |
Returns: a bool. For an empty range all_of and none_of return true, and any_of returns false.
Errors / undefined behavior: none for valid ranges; the predicate must not modify the elements.
Usage notes
- Empty ranges:
all_ofis vacuously true on an empty range. This surprises people who validate input: "all fields are valid" is true when there are no fields. Check for emptiness separately if it matters. - Short-circuit:
all_ofstops at the first false,any_ofat the first true,none_ofat the first true. Predicates with side effects may therefore run fewer times than the range size. - Complexity: at most
last - firstpredicate calls, O(n). - Relationships:
none_of(p)is!any_of(p), andall_of(p)isnone_of(!p). Choose whichever reads best. - Membership test: for a value rather than a predicate use
std::ranges::contains(C++23) orstd::find(...) != end. For a sorted range usebinary_search. - Ranges versions (C++20):
std::ranges::all_of,any_ofandnone_oftake a whole range and an optional projection. - Parallel overloads: an execution policy may be given first; see execution policies.