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';
}- 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