liveBook · Manning

Ranges API

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

The C++ ranges API is a standard-library interface for applying algorithms to ranges of elements without requiring explicit iterator pairs.

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

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

How deep it goes
Explains mapping, filtering, and reduction, and demonstrates a composed transform-and-filter pipeline.
Examples
Demonstrates transforming integers to absolute values, filtering evens, and accumulating their sum.
What you can do after
Apply C++ ranges and views to compose value transformations and filters before accumulation.
How it connects
Connects ranges to containers, lambdas, algorithms, and functional pipelines.

Also explained in

Compare how 2 books explain ranges API →

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.