Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::accumulate: a left fold over a range

std::accumulate combines a half-open range with an initial value and returns the final accumulator. The type of init affects the type and precision of every step.

Version: C++23

Syntax

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

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

std::accumulate, declared in <numeric>, starts with init and processes [first, last) as std::move(acc) + *first or binary_op(std::move(acc), *first). An empty range returns init without invoking the operation.

This is a left fold in iterator order, which matters for subtraction, string concatenation, and floating-point arithmetic. Integer 0 with double elements can cause unwanted conversions to int; use 0.0 for a floating-point accumulator.

The operation must not invalidate iterators or modify the processed range. A large total can overflow the accumulator type. std::reduce permits regrouping and parallel execution, but it need not produce identical floating-point rounding.

Examples

#include <iostream>
#include <numeric>
#include <vector>

int main() {
    const std::vector<int> values{1, 2, 4};
    std::cout << std::accumulate(values.begin(), values.end(), 0) << '\n';
}

Result

7

std::accumulate → 7

Sources