std::accumulate 定义于<numeric>头文件,用于对容器元素进行累加或自定义操作。基本语法为 std::accumulate(起始迭代器, 结束迭代器, 初始值),可选第四个参数为自定义函数或lambda表达式。例如对vector求和需包含头文件并使用正确类型初始值以避免精度丢失;double类型应使用0.0。支持通过lambda实现乘积等操作,如计算{1,2,3,4}的乘积结果为24。常用于求和、字符串拼接、配合lambda进行灵活聚合,替代for循环使代码更简洁安全。

在C++中,std::accumulate 是一个非常实用的算法,用于对容器中的元素进行累加或自定义操作。它定义在 <numeric> 头文件中,可以对数组、vector、list等支持迭代器的容器求和。
使用 std::accumulate 前需要引入头文件:
#include <numeric>函数原型如下:
std::accumulate(起始迭代器, 结束迭代器, 初始值)也可以提供第四个参数(自定义操作):
立即学习“C++免费学习笔记(深入)”;
std::accumulate(起始迭代器, 结束迭代器, 初始值, 自定义函数或lambda)下面是一个对 vector
#include <iostream>
#include <vector>
#include <numeric>
<p>int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 从0开始累加所有元素
int sum = std::accumulate(nums.begin(), nums.end(), 0);
std::cout << "总和:" << sum << std::endl; // 输出:15
return 0;}
如果容器是 double 类型,初始值应使用 0.0,否则可能因类型截断导致精度丢失:
std::vector<double> values = {1.1, 2.2, 3.3};
double total = std::accumulate(values.begin(), values.end(), 0.0); // 正确
若写成 0,会以 int 累加,再转为 double,虽结果正确但不推荐。
accumulate 不仅能求和,还能做其他累积操作。例如计算乘积:
std::vector<int> nums = {1, 2, 3, 4};
int product = std::accumulate(nums.begin(), nums.end(), 1,
[](int a, int b) { return a * b; });
std::cout << "乘积:" << product << std::endl; // 输出:24
基本上就这些。std::accumulate 简洁高效,适合替代手写 for 循环求和,代码更清晰也更安全。
以上就是c++++怎么使用std::accumulate对容器求和_c++累加算法accumulate用法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号