A running-total loop combines many values into one result. std::accumulate provides that pattern as a standard function from <numeric>. Supply the first iterator, the past-the-end iterator, and an initial value. The default operation adds each element to the running result in range order.
The initial value is part of the calculation, not just a placeholder. Starting with zero gives an ordinary sum. Starting with a delivery fee includes that fee before adding item prices. An empty range returns the initial value unchanged because there are no elements to add.
The type of that initial value also determines the running result's type. An integer 0 selects integer accumulation; a floating-point 0.0 selects floating-point accumulation. Here every amount is a small whole number of cents, so an int initial value is appropriate. For large values, you would need to choose a type and bounds that can hold the total.
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> lengths{5, 8, 2};
int total = std::accumulate(lengths.begin(), lengths.end(), 1);
std::cout << total << '\n';
}
The example prints 16. You can read the call as a running total that starts at one, then adds each length. In payable, the fee fills that starting-value role. Return the algorithm's result instead of adding the fee separately afterward. The empty-basket call is useful here: with no prices to visit, the result should still be the fee.
std::accumulate over prices, starting with fee. The supplied calls should produce Payable cents: 500 and Empty cents: 50.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.