std::accumulate
来自cppreference.com
<tbody>
</tbody>
| 在标头 <numeric> 定义
|
||
template< class InputIt, class T > T accumulate( InputIt first, InputIt last, T init ); |
(1) | (C++20 起为 constexpr) |
template< class InputIt, class T, class BinaryOp > T accumulate( InputIt first, InputIt last, T init, BinaryOp op ); |
(2) | (C++20 起为 constexpr) |
计算给定值 init 与范围 [first, last) 中各元素的和。
1) 以初始值
init 初始化(具有 T 类型的)累加器 acc,然后按顺序对范围 [first, last) 的每个迭代器 i 通过 acc = acc + *i(C++20 前)acc = std::move(acc) + *i(C++20 起) 进行累加。2) 以初始值
init 初始化(具有 T 类型的)累加器 acc,然后按顺序对范围 [first, last) 的每个迭代器 i 通过 acc = op(acc, *i)(C++20 前)acc = op(std::move(acc), *i)(C++20 起) 进行累加。如果满足以下任意条件,那么行为未定义:
T不可复制构造 (CopyConstructible) 。T不可复制赋值 (CopyAssignable) 。op会修改[first,last)的任何元素。op会使[first,last]中的任何迭代器或子范围失效。
参数
| first, last | - | 要累加的元素范围的迭代器对 |
| init | - | 累加的初值 |
| op | - | 被使用的二元函数对象。 该函数的签名应当等价于:
签名中并不需要有 |
| 类型要求 | ||
-InputIt 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
返回值
所有修改完成后的 acc。
可能的实现
| accumulate (1) |
|---|
template<class InputIt, class T>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init)
{
for (; first != last; ++first)
init = std::move(init) + *first; // C++20 起有 std::move
return init;
}
|
| accumulate (2) |
template<class InputIt, class T, class BinaryOperation>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op)
{
for (; first != last; ++first)
init = op(std::move(init), *first); // C++20 起有 std::move
return init;
}
|
注解
std::accumulate 进行左折叠。为进行右折叠,必须逆转二元运算符的实参顺序,并使用逆序迭代器。
如果使用类型推导,那么 op 就会对与 init 相同类型的值进行操作,这可能引入对迭代器元素非预期的转型,例如 std::accumulate(v.begin(), v.end(), 0) 在 v 是 std::vector<double> 时会给出错误的结果。
示例
运行此代码
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = std::accumulate(v.begin(), v.end(), 0);
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
auto dash_fold = [](std::string a, int b)
{
return std::move(a) + '-' + std::to_string(b);
};
std::string s = std::accumulate(std::next(v.begin()), v.end(),
std::to_string(v[0]), // 用首元素开始
dash_fold);
// 使用逆向迭代器右折叠
std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(),
std::to_string(v.back()), // 用末元素开始
dash_fold);
std::cout << "和:" << sum << '\n'
<< "积:" << product << '\n'
<< "以短横线分隔的字符串:" << s << '\n'
<< "以短横线分隔的字符串(右折叠):" << rs << '\n';
}
输出:
和:55
积:3628800
以短横线分隔的字符串:1-2-3-4-5-6-7-8-9-10
以短横线分隔的字符串(右折叠):10-9-8-7-6-5-4-3-2-1
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 242 | C++98 | op 不能有任何副作用
|
它不能修改涉及到的范围 |
参阅
| 计算范围中相邻元素的差 (函数模板) | |
| 计算两个范围中元素的内积 (函数模板) | |
| 计算范围中元素的部分和 (函数模板) | |
(C++17) |
类似 std::accumulate,但不依序执行 (函数模板) |
(C++23) |
左折叠范围中元素 (算法函数对象) |