std::accumulate

Header: <numeric>

std::accumulate accumulates elements in [first, last) as a left fold, starting from init.

The first overload updates the accumulator with operator+. The second overload updates it with a user-provided binary operation.

# Declarations

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

(constexpr since C++20)

template< class InputIt, class T, class BinaryOp >
T accumulate( InputIt first, InputIt last, T init, BinaryOp op );

(constexpr since C++20)

# Parameters

op must not invalidate iterators or subranges in [first, last), and must not modify elements in that range.

# Type requirements

# Semantics

Let acc be the accumulator initialized from init.

# Return value

Final value of the accumulator after processing all elements.

# Complexity

Let N = std::distance(first, last).

# Exceptions

Any exception thrown by operator+, op, iterator operations, or assignments to the accumulator is propagated.

# Notes

std::accumulate performs a left fold. To emulate a right fold, use reverse iterators and a matching operation order.

Type deduction for init matters. For example, std::accumulate(v.begin(), v.end(), 0) with v of type std::vector<double> performs integer accumulation and truncates intermediate results.

# Example

#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
 
int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    int sum = std::accumulate(v.begin(), v.end(), 0);
    int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
 
    auto dash_fold = [](std::string a, int b)
    {
        return std::move(a) + '-' + std::to_string(b);
    };
 
    std::string s = std::accumulate(std::next(v.begin()), v.end(),
                                    std::to_string(v[0]), // start with first element
                                    dash_fold);
 
    // Right fold using reverse iterators
    std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(),
                                     std::to_string(v.back()), // start with last element
                                     dash_fold);
 
    std::cout << "sum: " << sum << '\n'
              << "product: " << product << '\n'
              << "dash-separated string: " << s << '\n'
              << "dash-separated string (right-folded): " << rs << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 242C++98op could not have side effectsit cannot modify the ranges involved

# See also