stdaccumulate
在標題 <numeric> 中定義
template<class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init); // (1)
template<class InputIterator, class T, class BinaryOperation>
T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation f); // (2)
功效:
std::accumulate 使用 f 函式對 [first, last) 執行摺疊操作,以 init 為累加器值。
實際上它相當於:
T acc = init;
for (auto it = first; first != last; ++it)
acc = f(acc, *it);
return acc;
在版本(1)中,使用 operator+代替 f,因此在容器上累積相當於容器元素的總和。
引數:
first, last - 應用 f 的範圍。
init - 累加器的初始值。
f - 二進位制摺疊功能。
返回值:
f 應用的累計價值。
複雜:
O(n×k) ,其中 n 是從 first 到 last 的距離, O(k) 是 f 函式的複雜度。
例:
簡單的例子:
std::vector<int> v { 2, 3, 4 };
auto sum = std::accumulate(v.begin(), v.end(), 1);
std::cout << sum << std::endl;
輸出:
10
將數字轉換為數字:
Version < C++ 11
class Converter {
public:
int operator()(int a, int d) const { return a * 10 + d; }
};
然後
const int ds[3] = {1, 2, 3};
int n = std::accumulate(ds, ds + 3, 0, Converter());
std::cout << n << std::endl;
Version >= C++ 11
const std::vector<int> ds = {1, 2, 3};
int n = std::accumulate(ds.begin(), ds.end(),
0,
[](int a, int d) { return a * 10 + d; });
std::cout << n << std::endl;
輸出:
123