Daily bit(e) of C++ | std::for_each
Daily bit(e) of C++ ♻️60, The algorithm that applies an invocable to each element of a range in-order: std::for_each.
The std::for_each algorithm invokes the provided invocable on each range element in order (left-to-right), ignoring the result. The invocable can be stateful, and the algorithm returns it in its final state (after being applied to all elements).
While the range-based for-loop has mostly replaced the use cases for std::for_each, it still comes in handy as a trivial parallelization tool through the C++17 parallel version. It can also offer a more readable solution when using the C++20 range version with a projection.
Note that the parallel version doesn't operate strictly left-to-right and does not return the invocable.