std::reduce
std::reduce 是 C++17 引入的標準函數,用於對範圍內的元素進行歸約操作。
它類似於 std::accumulate,但有一些重要的區別,包括默認使用並行執行和一些優化,真是太方便了!
累加範圍內的所有元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <numeric>
#include <vector>
#include <iostream>
#include <execution> // 用於並行執行的標頭檔案
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 預設使用 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;
}
執行結果:
累乘範圍內的所有元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <numeric>
#include <vector>
#include <iostream>
#include <execution> // 用於並行執行的標頭檔案
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用乘法進行歸約
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;
}
其中 std::execution::par 指定使用並行策略。
執行結果:
使用時機
std::reduce 提供了一個靈活且高效的方式來對範圍內的元素進行歸約操作,特別是在需要高效處理大數據集的情況下,並行策略可以顯著提高性能。
在大部分的情況下,std::reduce 都可以取代 std::accumulate 使用。
快去用用看吧!


