-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
30 lines (27 loc) · 1021 Bytes
/
main.cpp
File metadata and controls
30 lines (27 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
This shows using parallel transform_reduce from C++17
to perform a fold (reduce) operation on a range of values. e.g. sum up 100 values in parallel
*/
#include <vector>
#include <numeric> // std::transform_reduce
#include <functional> // std::plus
#include <iostream>
#include <execution> // std::execution::par
int
main()
{
std::vector<int> numbers(100);
// Initialize the vector with values 1 to 100
std::iota(numbers.begin(), numbers.end(), 1);
// Use parallel transform_reduce to sum the values in parallel
int sum = std::transform_reduce(
std::execution::par, // parallel execution policy parallel or std::execution::seq for sequential
numbers.begin(),
numbers.end(),
0, // initial value
std::plus<int>{}, // binary operation to combine results
[](int v) { return v; } // unary operation to transform each element
);
std::cout << "Sum of numbers from 1 to 100: " << sum << '\n';
return 0;
}