Defined in header <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)
Effects:
std::accumulate performs fold operation using f
function on range [first, last)
starting with init
as accumulator value.
Effectively it's equivalent of:
T acc = init;
for (auto it = first; first != last; ++it)
acc = f(acc, *it);
return acc;
In version (1) operator+
is used in place of f
, so accumulate over container is equivalent of sum of container elements.
Parameters:
first, last
- the range to apply f
to.
init
- initial value of accumulator.
f
- binary folding function.
Return value:
Accumulated value of f
applications.
Complexity:
O(n×k), where n is the distance from first
to last
, O(k) is complexity of f
function.
Example:
Simple sum example:
std::vector<int> v { 2, 3, 4 };
auto sum = std::accumulate(v.begin(), v.end(), 1);
std::cout << sum << std::endl;
Output:
10
Convert digits to number:
class Converter {
public:
int operator()(int a, int d) const { return a * 10 + d; }
};
and later
const int ds[3] = {1, 2, 3};
int n = std::accumulate(ds, ds + 3, 0, Converter());
std::cout << n << std::endl;
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;
Output:
123