本文与reduce函数学习的知识深度很浅,主要是记录一下使用reduce
来简化代码,高效解题。
参考资料:
https://cppreference.cn/w/cpp/algorithm/reduce
1. reduce
函数概述
reduce
函数类似于 accumulate
,但它允许更灵活的并行化和元素分组。头文件是 <numeric>
。
函数原型中的几种重载形式:
#include <numeric>
#include <iostream>// 没有初始值
template< class InputIt >
typename std::iterator_traits<InputIt>::value_type
reduce( InputIt first, InputIt last );// 有初始值
template< class InputIt, class T >
T reduce( InputIt first, InputIt last, T init );// 自定义操作
template< class InputIt, class T, class BinaryOp >
T reduce( InputIt first, InputIt last, T init, BinaryOp op );
2. 简单案例
简单求和
#include <iostream>
#include <vector>
#include <numeric>
int main() {vector<int> numbers = {1, 2, 3, 4, 5};int sum = reduce(numbers.begin(), numbers.end());cout << "Sum : " << sum << endl;return 0;
}
自定义操作
reduce
函数还可以使用自定义的二元操作函数。下面计算数组中所有元素的乘积:
#include <iostream>
#include <vector>
#include <numeric>
int main() {vector<int> numbers = {1, 2, 3, 4, 5};int ret= reduce(numbers.begin(), numbers.end(), 1, [](int a, int b) {return a * b;});cout << "ret: " << ret<< endl;return 0;
}
并行化
从 C++17 开始,reduce
支持并行化执行,加速计算。
#include <iostream>
#include <vector>
#include <numeric>
#include <execution>
int main() {vector<int> numbers = {1, 2, 3, 4, 5};// 使用并行策略int sum = reduce(std::execution::par, numbers.begin(), numbers.end());cout << "Sum (parallel): " << sum << endl;return 0;
}
3. 简单练习
使用 reduce
函数计算以所有元素的平方和:
#include <iostream>
#include <vector>
#include <numeric>int main() {std::vector<int> numbers = {1, 2, 3, 4, 5};int sum_of_squares = reduce(numbers.begin(), numbers.end(), 0, [](int a, int b) {return a + b * b;});std::cout << "Sum of squares: " << sum_of_squares << std::endl;return 0;
}
使用 reduce
函数和并行策略计算以下数组中所有元素的最大值:
std::vector<int> numbers = {1, 3, 91, 12, 4};
#include <iostream>
#include <vector>
#include <numeric>
#include <execution>int main() {std::vector<int> numbers = {10, 20, 30, 40, 50};int max_value = reduce(std::execution::par, numbers.begin(), numbers.end(), numbers[0], [](int a, int b) {return a > b ? a : b;});std::cout << "Maximum value: " << max_value << std::endl;return 0;
}