liveBook · Manning

All_of

As explained in Learn C++ by Example

all_of is a C++ standard algorithm that tests whether a unary predicate is true for every element in a sequence or range.

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

How Learn C++ by Example covers it

How deep it goes
Explains predicates, lambdas, iterator pairs, ranges, and mutable captures through practical checks, without descending into algorithm implementation internals.
Examples
Uses non-negative row values and triangle-number verification as concrete all_of checks.
What it assumes
Assumes basic containers and loops, while teaching unary predicates, lambda syntax, captures, and mutable copied captures.
What you can do after
Apply all_of with iterator pairs or ranges and write predicates as named functions or lambdas.
How it connects
Connects all_of with unary predicates, lambda expressions, iterators, ranges, assertions, and mutable capture.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.