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
