Library contents

C++ std::accumulate

std::accumulate folds a range from left to right, starting with the value and type of its initial accumulator.

A simple example

std::accumulate

  1. Start with 1, 2, 3
  2. Do this Start at 0 and add each value
  3. Result 6
The running total changes from 0 to 1, then 3, then 6.

Syntax

C++ syntax
std::accumulate(first, last, initial)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Total a batch using a wide accumulator

A batch can contain enough readings, or large enough values, to exceed a simple implementation's assumptions. Select a safe representation or comparison before combining, storing or ordering those inputs.

First output line4000000000
lesson.cpp
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<long long> amounts{2000000000LL, 2000000000LL};
    std::cout << std::accumulate(amounts.begin(), amounts.end(), 0LL) << '\n';
    std::cout << std::accumulate(amounts.begin(), amounts.begin(), 0LL) << '\n';
    return 0;
}
Output
4000000000
0

The initial 0LL selects long long. Passing an int zero could overflow while summing these values on common platforms. An empty range returns its initial value.

C++ working draft for std::accumulate

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The shift total is the sum of the listed counts. What total goes on the handover slip?

Given6 · 2 · 6 · 0
Worked result14

Review print quantities

A print room records four job quantities, including a cancelled job. The shift total is the sum of the listed counts. What total goes on the handover slip?

Given3 · 0 · 8 · 3
Worked result14