liveBook · Manning

Std::accumulate

As explained in 100 C++ Mistakes and How to Avoid Them

std::accumulate is a C++ standard-library algorithm that folds a range of values into one result using an initial value and an accumulation operation.

std::accumulate folds every value in an input range into one result. It takes the first and last iterators plus an initial value, such as zero for a sum. section 4.4

Mistake: treating accumulation as another independent loop. A range pipeline can transform and filter values first, but std::accumulate still requires begin and end iterators, limiting direct composition. section 4.4

Summing filtered values

auto evens = vals | std::views::transform([](int x) { return abs(x); }) | std::views::filter([](int x) { return x % 2 == 0; }); auto sum = std::accumulate(evens.begin(), evens.end(), 0); The pipeline produces absolute even values; std::accumulate reduces them to one sum. The approach avoids a separate summing loop, although the iterator-based call is not fully pipeline-composable. section 4.4

Listing 4.9 Composed functions on a value sequence
int main() {
    std::vector<int> vals { 42, 3, 7 -9, 0, 22, 23, -7, 22 };
 
    auto evens = vals
        | std::views::transform([](int x) { return abs(x); })
        | std::views::filter([](int x){ return x % 2 == 0; }); #1
    auto sum = std::accumulate(evens.begin(), evens.end(), 0); #2
 
    std::cout << sum << '\n';
    return 0;
}

Compare the composed transform/filter pipeline with the accumulation call. section 4.4

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains reduction, initial values, and iterator boundaries, but does not detail accumulation-operation customization.
Examples
Uses absolute-value transformation, even-value filtering, and summation over an integer vector.
What you can do after
Apply it via the C++ standard library to reduce a range after range-based transformations or filtering.
How it connects
Connects std::accumulate with C++ ranges, range adapters, containers, and lambdas.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.