A range adapter creates a view by lazily transforming or selecting elements from a range. Pipelines can replace several loops and temporary containers with readable, composable operations. section 4.4
Transform, filter, then reduce
Given a vector of integers, apply std::views::transform to take absolute values, pipe the result into std::views::filter to keep evens, and use std::accumulate to compute the sum. The pipeline is compact, but accumulate still requires begin and end iterators and cannot join the pipeline directly. 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 range-adapter pipeline with the separate loops and intermediate evens container used by the traditional approach. section 4.4
Use range adapters carefully:
- Prefer them when they reduce container-processing overhead and make the operation easier to read. section 4.4
- Check composability: not every range-oriented function can participate in a pipeline. section 4.4
