Ranges let container algorithms work without explicit iterator pairs. They also let you compose operations as a pipeline, making a sequence of transformations easier to read than separate loops and intermediate containers. section 4.4 section 4.6
A value-processing pipeline can combine three operations:
- Map each input value to one output value with transform. section 4.4
- Keep values matching a predicate with filter. section 4.4
- Reduce the resulting sequence to a value, such as a sum. 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;
}
This example transforms values to their absolute values, filters for even values, then accumulates the result. It contrasts a composed pipeline with separate loops and an intermediate container. section 4.4
When maintaining existing code, consider replacing suitable iterator-pair calls with the ranges API; weigh readability and simplicity against compatibility constraints. section 4.6

