What is the std::accumulate() function in C++?

std::accumulate() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, initial value, and (by default) computes the sum of the given initial value and the elements in the given range.

The function can also​ be used for left folding. This is done by passing in a binary operation function object that takes the current accumulation value and the value of the current element, and returns the new accumulation value.

Take a look at the function signature of std::accumulate() below:

Function signature of std::accumulate

Code

Using std::accumulate()

Using std::accumulate with a built-in binary predicate

In the following examples, an array of integers are summed and folded:

Using std::accumulate with a custom binary predicate