liveBook · Manning

Range adapter

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

A range adapter is a C++ standard-library component that creates a view of a range by applying a lazy transformation or selection operation.

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

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

How deep it goes
Demonstrates transformation, filtering, and reduction, but stops short of fully composable accumulation.
Examples
Uses a vector of integers, absolute-value transformation, even-value filtering, and summation.
What you can do after
Apply std::views::transform and std::views::filter to compose container-processing pipelines.
How it connects
Connects ranges with containers, lambdas, STL algorithms, iterators, and functional programming.

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.