Home Item 22 - reduce(English)
Post
Cancel

Item 22 - reduce(English)

std::reduce

std::reduce is a standard function introduced in C++17 for performing reduction operations on a range of elements.

It is similar to std::accumulate, but with some important differences, including the default use of parallel execution and certain optimizations, making it very convenient!

Summing All Elements in a Range

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <numeric>
#include <vector>
#include <iostream>
#include <execution> // Header for parallel execution

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Default to sequential execution using std::execution::seq
    int sum = std::reduce(std::execution::seq, vec.begin(), vec.end(), 0);

    std::cout << "Sum: " << sum << std::endl; // Output: Sum: 15
    return 0;
}

Execution result:

Desktop View

Multiplying All Elements in a Range

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <numeric>
#include <vector>
#include <iostream>
#include <execution>  // Header for parallel execution

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

     // Perform reduction using multiplication
    int product = std::reduce(std::execution::par, vec.begin(), vec.end(), 1, std::multiplies<int>());

    std::cout << "Product: " << product << std::endl; // Output: Product: 120
    return 0;
}

Here, std::execution::par specifies the use of a parallel policy.

Execution result:

Desktop View

Usage Scenarios

std::reduce provides a flexible and efficient way to perform reduction operations on a range of elements. It is especially useful in situations that require efficient processing of large data sets, where parallel policies can significantly improve performance.

In most cases, std::reduce can replace std::accumulate.

Give it a try!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍