all_of checks whether a unary predicate returns true for every value in a sequence or range. It offers a direct alternative to writing a loop that tests each element. section 2.3.4
Use all_of with a predicate that expresses the property every element must satisfy:
- Pass iterator pairs to std::all_of, such as row.begin() and row.end(), followed by a lambda or named function. section 2.3.4
- Use a lambda when the test is small; [](int x) { return x >= 0; } checks that each integer is non-negative. section 2.3.4
- Use std::ranges::all_of with a range directly when the data is already represented as a range. section 2.3.4
Checking triangle numbers
A loop can compare each triangle number with its formula. all_of expresses the same test compactly, while a mutable lambda keeps a copied counter: assert(std::all_of(triangle_numbers.begin(), triangle_numbers.end(), [n = 0](int x) mutable { ++n; return x == n * (n + 1) / 2; })); The mutable keyword permits modification of the variable captured by copy. section 9.1.3
std::all_of(row.begin(), row.end(), [](int x) { return x >= 0; })
See the compact iterator-based form for checking that every value in row is non-negative. section 2.3.4
