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
- Start with 1, 2, 3
- Do this Start at 0 and add each value
- Result 6
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.
#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;
}
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
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?
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?