...

/

For_Each and Reduce Algorithms

For_Each and Reduce Algorithms

This lesson goes into the details of reduce algorithm and its working.

for_each Algorithm

In the serial version of for_each, the version that was available before C++17 you get a unary function as a return value from the algorithm.

Returning such an object is not possible in a parallel version, as the order of invocations is indeterminate.

Here’s a basic example:

Press + to interact
void ForEachTest() {
std::vector<int> v(100);
std::iota(v.begin(), v.end(), 0);
std::for_each(std::execution::par, v.begin(), v.end(),
[](int& i) { i += 10; });
std::for_each_n(std::execution::par, v.begin(), v.size() / 2,
[](int& i) { i += 10; });
}
int main() {
ForEachTest();
return 0;
}

The first for_each algorithm will update all of the elements of a vector, while the second execution will work only on the first half of the container.

Understan

...