代码点读机 / C++ / std::accumulate

std::accumulate C++ · STL

把范围内元素按指定二元操作累加(默认求和),返回一个累积值。

怎么用

std::accumulate(开头, 结尾, 初值);

小例子

#include <numeric>
#include <vector>
std::vector<int> v = {1, 2, 3};
int s = std::accumulate(v.begin(), v.end(), 0);
std::cout << s;

运行结果

6

提醒:头文件是 <numeric>;可用 lambda 自定义累加方式,如求积

官方文档:https://en.cppreference.com/w/cpp/algorithm/accumulate

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← C++全部词条