std accumulate

suggest change

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)


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.


first, last - the range to apply f to. init - initial value of accumulator. f - binary folding function.

Return value:

Accumulated value of f applications.


O(n×k), where n is the distance from first to last, O(k) is complexity of f function.


Simple sum example:

std::vector<int> v { 2, 3, 4 };
auto sum = std::accumulate(v.begin(), v.end(), 1);
std::cout << sum << std::endl;



Convert digits to number:

class Converter {
    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(),
                        [](int a, int d) { return a * 10 + d; });
std::cout << n << std::endl;



Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents