C++ std::accumulate
Combine a sequence of whole-unit prices into a single total.
A simple example
std::accumulate
- Start with 1, 2, 3
- Do this Start at 0 and add each value
- Result 6
Syntax
std::accumulate(prices.begin(), prices.end(), 0)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonAdd the prices on a shopping list
A shopper compares the prices in a basket before paying. Work from the prices actually present in the list so a total or minimum reflects the same set of items as the receipt.
#include <algorithm>
#include <numeric>
#include <iostream>
#include <vector>
int main() {
const std::vector<int> prices {8, 3, 12, 3};
std::cout << (std::accumulate(prices.begin(), prices.end(), 0)) << "\n";
return 0;
}
26
The four prices add up to 8 + 3 + 12 + 3, giving 26. Both three-unit items count.
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?
What to watch for
Use integer minor units or decimal arithmetic for prices with fractional currency units.