std::accumulate folds a range into one value, such as a total with an optional starting amount.

accumulate `std::accumulate` visits each value in a range and combines it into a running result.
initial value The initial value controls where the total starts before the first element is added.

Accumulate Totals

shipping
accumulate_totals.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> prices{12, 8, 5};
    int shipping = 4;

    int total = std::accumulate(prices.begin(), prices.end(), shipping);

    std::cout << "shipping=" << shipping << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> prices{12, 8, 5};
    int shipping = 0;

    int total = std::accumulate(prices.begin(), prices.end(), shipping);

    std::cout << "shipping=" << shipping << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> prices{12, 8, 5};
    int shipping = 10;

    int total = std::accumulate(prices.begin(), prices.end(), shipping);

    std::cout << "shipping=" << shipping << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
  1. prices ← [12, 8, 5], shipping ← 4, total ← 29

    5int main() {6    std::vector<int> prices→ [12, 8, 5]{12, 8, 5};7    int shipping→ 4 = 4; //@shipping=0, 1089    int total→ 29 = std::accumulate(prices[12, 8, 5].begin(), prices.end(), shipping4);1011    std::cout << "shipping=" << shipping4 << std::endl;12    std::cout << "total=" << total29 << std::endl;13    return 0;14}
    outputshipping=4
    total=29
  1. prices ← [12, 8, 5], shipping ← 0, total ← 25

    5int main() {6    std::vector<int> prices→ [12, 8, 5]{12, 8, 5};7    int shipping→ 0 = 0;89    int total→ 25 = std::accumulate(prices[12, 8, 5].begin(), prices.end(), shipping0);1011    std::cout << "shipping=" << shipping0 << std::endl;12    std::cout << "total=" << total25 << std::endl;13    return 0;14}
    outputshipping=0
    total=25
  1. prices ← [12, 8, 5], shipping ← 10, total ← 35

    5int main() {6    std::vector<int> prices→ [12, 8, 5]{12, 8, 5};7    int shipping→ 10 = 10;89    int total→ 35 = std::accumulate(prices[12, 8, 5].begin(), prices.end(), shipping10);1011    std::cout << "shipping=" << shipping10 << std::endl;12    std::cout << "total=" << total35 << std::endl;13    return 0;14}
    outputshipping=10
    total=35