CodeBlanks Logo Icon CodeBlanks

std::accumulate

Learn aggregation with std::accumulate.

std::accumulate

std::accumulate combines all elements in a range. By default it sums them: int sum = std::accumulate(v.begin(), v.end(), 0);. The third parameter is the initial value; the accumulation starts from this value.

std::accumulate is defined in <numeric> (not in algorithm). The initial value sets the result type: 0 sums as int, 0.0 as double. You can pass a custom operation as the fourth parameter; for example std::multiplies<int>() for multiplication. This way accumulate is not just summation but a general 'fold' operation.

Initial value and type

The initial value sets not only where the sum starts but also the type of the result. Writing 0 sums as int, writing 0.0 sums as double. For a double vector, writing 0 loses the fractional part.

Example: for std::vector<double> prices = {9.99, 14.50, 3.75}; you write std::accumulate(prices.begin(), prices.end(), 0.0). This gives 28.24. If you write 0 the result is 28 (no fraction). That is why the initial value must match the vector type.

Practice Print the sum

For v = {1, 2, 3, 4, 5}, find the sum with std::accumulate and print it with std::cout. Use 0 as the initial value. Remember #include <numeric> is required.

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    // Print the sum with std::accumulate
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <numeric>

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

Expected output

15

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
std::accumulate Sum/fold
v.begin() Range start
v.end() Range end
0 (third param) Initial value

2 What is the third parameter of std::accumulate?

main.cpp
std::accumulate(v.begin(), v.end(), ???);
  • The last element
  • A function object
  • An index
  • The initial value Correct answer

Explanation: The third parameter is the initial value.

3 Complete the accumulate call

Question
int sum = std::____(v.begin(), v.end(), 0);
Answer
int sum = std::accumulate(v.begin(), v.end(), 0);

Explanation: std::accumulate sums the elements.

All lessons in Intermediate