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)

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

Feedback about page:

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


Standard library algorithms:
* std accumulate

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
85 Standard library algorithms
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype