Search⌘ K

More Algorithms

Explore how to apply transform_reduce for fused transform and reduction operations and use exclusive and inclusive scan algorithms in parallel STL. Understand their roles in improving performance with parallel execution and learn applications like prefix sums for efficient data handling.

transform_reduce - Fused Algorithm

To get even more flexibility and performance, the reduce algorithm also has a version where you can apply a transform operation before performing the reduction.

C++
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto sumTransformed = std::transform_reduce(std::execution::par,
v.begin(),
v.end(),
0,
std::plus<int>{},
[](const int& i) { return i * 2; }
);
cout << sumTransformed;
return 0;
}

​The above code will first execute the unary functor - the lambda that doubles the input value; then the results will be reduced into a single sum.

The fused version will be faster than using two algorithms: std::reduce ...