Codectionary / Developer documentation / C++

C++ std::accumulate totals

accumulate folds a range from left to right into an initial value. The initial value determines the accumulator type, which matters for floating-point totals and integer overflow. This example requires C++11 or later.

Syntax

auto total = std::accumulate(first, last, initial);

Examples

C++ std::accumulate totals

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <numeric>
#include <vector>
#include <iostream>
int main() {
    std::vector<double> prices{1.5, 2.25, 3.0};
    double total = std::accumulate(prices.begin(), prices.end(), 0.0);
    std::cout << total << '\n';
}
  1. Output: 6.75. Using integer 0 as the initial value would repeatedly truncate intermediate sums.

Best practices

  • Choose an accumulator type that holds the intended range and precision; the library does not prevent arithmetic overflow.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading