欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > C++ 中的reduce函数使用指南

C++ 中的reduce函数使用指南

2025/2/28 11:39:27 来源:https://blog.csdn.net/nyxdsb/article/details/145894126  浏览:    关键词:C++ 中的reduce函数使用指南

本文与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;
}

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词