C++AlgorithmsIntermediate

std::accumulate()

Computes the sum of elements in a range `[first, last)` starting with an initial value, or applies a custom binary operation.

Review the syntaxStudy the examplesOpen the coding app
std::accumulate(first, last, initial_value, [binary_op]);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Computes the sum of elements in a range `[first, last)` starting with an initial value, or applies a custom binary operation.

The `std::accumulate()` algorithm, found in the `<numeric>` header, is a powerful tool for performing a 'fold' or 'reduce' operation over a range of elements. It iterates through the elements in the range `[first, last)`, starting with an `alue`, and applies a binary operation to accumulate a single result. By default, the binary operation is addition (`+`), so it computes the sum of all elements. However, an optional `p` (a lambda, function pointer, or functor) can be provided to perform any custom operation, such as multiplication, concatenation, or combining complex objects. The `alue` is crucial as it sets the starting point for the accumulation and also determines the return type of the function. For example, if `alue` is an `int`, the result will be an `int`, even if the elements are `double`. This algorithm has a linear time complexity, O(N), as it visits each element in the range exactly once. It's highly versatile for tasks like summing numbers, concatenating strings, calculating products, or performing custom aggregations on collections, making it a staple for functional-style programming in C++.

Quick reference

Syntax

std::accumulate(first, last, initial_value, [binary_op]);

Inputs

Parameters

firstInputIterator · An iterator to the beginning of the range.
lastInputIterator · An iterator to the end of the range (one past the last element).
initial_valueT · The initial value of the sum or accumulation. Its type determines the return type.
binary_op (optional)BinaryFunction · An optional binary function that takes the current accumulated value and an element, returning the new accumulated value.

See it in practice

Examples

1

Summing integers in a vector

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

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int sum = std::accumulate(numbers.begin(), numbers.end(), 0);

    std::cout << "Sum of numbers: " << sum << std::endl;
    return 0;
}
Output:
Sum of numbers: 15

The `std::accumulate()` function calculates the sum of all elements in the `numbers` vector, starting with an initial value of 0.

2

Calculating product using a custom binary operation (lambda)

#include <iostream>
#include <vector>
#include <numeric>
#include <functional> // For std::multiplies

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int product = std::accumulate(numbers.begin(), numbers.end(), 1, std::multiplies<int>());
    // Or using a lambda:
    // int product = std::accumulate(numbers.begin(), numbers.end(), 1, [](int a, int b){ return a * b; });

    std::cout << "Product of numbers: " << product << std::endl;
    return 0;
}
Output:
Product of numbers: 120

By providing `std::multiplies<int>()` (or a lambda for multiplication) as the binary operation, `std::accumulate()` calculates the product of the elements, starting with 1.

3

Concatenating strings

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

int main() {
    std::vector<std::string> words = {"Hello", " ", "World", "!"};
    std::string sentence = std::accumulate(words.begin(), words.end(), std::string(""));

    std::cout << "Concatenated string: \"" << sentence << "\"" << std::endl;
    return 0;
}
Output:
Concatenated string: "Hello World!"

Using an empty `std::string` as the initial value and the default `+` operator, `std::accumulate()` concatenates all strings in the vector.

Debug faster

Common Errors

1

Logical Error

Cause: Incorrect `initial_value` type, which dictates the return type and intermediate accumulation type. For example, using `0` for `double` sums might truncate results.

Fix: Ensure `initial_value` has the desired type for the accumulation. For `double` sums, use `0.0`; for `long long`, use `0LL`, etc.

std::vector<double> doubles = {0.1, 0.2, 0.3};
int sum_int = std::accumulate(doubles.begin(), doubles.end(), 0); // sum_int will be 0, not 0.6
2

Compilation Error

Cause: Providing a `binary_op` that does not match the expected signature (e.g., takes three arguments instead of two).

Fix: The `binary_op` must accept two arguments: the current accumulated value and the current element, and return the new accumulated value.

std::accumulate(v.begin(), v.end(), 0, [](int a, int b, int c){ return a + b + c; }); // Too many arguments

Runtime support

Compatibility

GCC, Clang, MSVCN/AC++98+

Source: cppreference.com

Common questions

Frequently Asked Questions

Computes the sum of elements in a range `[first, last)` starting with an initial value, or applies a custom binary operation.

first: An iterator to the beginning of the range. last: An iterator to the end of the range (one past the last element). alue: The initial value of the sum or accumulation. Its type determines the return type. p: An optional binary function that takes the current accumulated value and an element, returning the new accumulated value.

Logical Error: Ensure `alue` has the desired type for the accumulation. For `double` sums, use `0.0`; for `long long`, use `0LL`, etc. Compilation Error: The `p` must accept two arguments: the current accumulated value and the current element, and return the new accumulated value.