C++ Reference ยท Algorithms
The std::for_each algorithm
Reference for C++ std::for_each and for_each_n: apply a function to every element of a range, modify elements by reference, and how it compares to range-for.
std::for_each calls a function once for every element in a range, in order. The function receives the element by reference if its parameter is a reference, so it can modify the elements in place. std::for_each_n does the same for the first n elements.
In modern code a range-based for loop is usually clearer. for_each earns its place when you already have a named function object, when you want to apply it to a sub-range, or when you need the parallel overloads.
std::for_each(v.begin(), v.end(), [](int& x) { x *= 2; });
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 Fn> Fn for_each(InputIt first, InputIt last, Fn f); template<class InputIt, class Size, class Fn> InputIt for_each_n(InputIt first, Size n, Fn f); // C++17
| Name | Description |
|---|---|
first, last |
The half-open range [first, last). |
n |
Number of elements to process (for_each_n); must not be negative. |
f |
Called as f(*it) for each element. Its return value is ignored. |
Returns: for_each returns f (moved), which lets you read the state of a function object afterwards. for_each_n returns the iterator one past the last element processed.
Errors / undefined behavior: f must not invalidate iterators in the range, for example by erasing elements from the container being traversed.
Usage notes
- Exactly
last - firstcalls, in order from first to last (the plain version guarantees the order; parallel overloads do not). - Modifying elements: the parameter must be a non-const reference. With a by-value parameter the function changes only a copy.
- Range-for instead:
for (auto& x : v) { ... }does the same with less syntax, supportsbreakandcontinue, and is usually preferred. You cannot stopfor_eachearly other than by throwing. - Use it with a name:
for_each(v.begin(), v.end(), print_item)reads well when the callable already exists. - Stateful functors: the function object is copied into the algorithm, so capture by reference (or use the returned copy) to get results out. This is why the returned value exists.
- Parallel overloads (C++17): with an execution policy the calls may run concurrently and the function must be thread-safe; the return value is
voidforfor_eachin that case. See execution policies. - Ranges version (C++20):
std::ranges::for_eachreturns a struct with the end iterator and the function. - Not for building results: to produce a new sequence use
std::transform.