std::accumulate是C++ STL中用于数值累加的通用函数,支持默认求和及自定义二元操作,返回类型由初始值类型决定,需注意类型匹配与溢出风险。
std::accumulate 是 C++ STL 头文件里最常用、最直观的数值累加函数,它能把一个范围内的所有元素“加起来”,但不止于加法——还能自定义运算规则。
最常见场景就是对容器(如 vector、array)做求和:
#include
operator+,所以元素类型必须支持加法例子:
vector第四个参数可以传入任意接受两个参数的可调用对象(lambda、函数指针、functor),实现乘积、最大值、字符串拼接等:
op(init, *first),不是跳过 init例子(计算乘积):
vectoraccumulate 的返回类型完全由第三个参数(init)的类型决定,和容器元素类型无关:
int,哪怕 vector 是 long long,结果也会被截断成 int0LL、0.0、ll(0)
反例:
vectoraccumulate 不仅能算数,还能构建更复杂逻辑:
accumulate(v.begin(), v.end(), 0, [](int n, int x) { return n + (x > 0 ? 1 : 0); })
accumulate(vstr.begin(), vstr.end(), string{}, [](const string& a, const string& b) { return a + " " + b; })
accumulate(zip_iter, ..., 0.0, [](double s, auto p) { return s + p.f
irst * p.second; })(需配合 zip_view 或手动配对)注意:它不检查空范围——空区间时直接返回 init,这是合理且安全的设计。
基本上就这些。用熟了你会发现,它比手写 for 循环更简洁,比 reduce 更易理解,是日常数值聚合的首选工具。