C++advancedcpp20

Ranges and views

Lazy, composable pipelines that replace nested loops and temporary vectors.

The C++20 <ranges> library turns filter, transform, and take into pipe-composable adaptors, and lets std::ranges algorithms take a whole range instead of two iterators.

The C++20 <ranges> library is two things at once. First, every <algorithm> gains a std::ranges:: overload that accepts a whole range β€” std::ranges::sort(v) instead of std::sort(v.begin(), v.end()). No more passing begin()/end() pairs, and no more accidentally mixing iterators from two different containers.

Second, the std::views namespace provides range adaptors: lightweight, lazy views over an existing range. views::filter, views::transform, and views::take do not own or copy data β€” they describe a computation that runs element-by-element only as you iterate. Because nothing materialises, chaining several is cheap.

Piping with |

Adaptors compose left-to-right with operator|, the same pipe you know from the shell. nums | views::filter(pred) | views::transform(fn) reads as a data pipeline: keep the elements matching pred, then map each through fn. Evaluation is lazy and single-pass β€” an element flows all the way through the chain before the next one is pulled, so no intermediate container is ever built.

Infinite ranges, finite results

Because views are lazy, a range can be unbounded. views::iota(1) yields 1, 2, 3, … forever, and views::take(n) caps any view at its first n elements. Composing an infinite generator with take is the idiomatic way to produce "the first N of something" without writing a counter loop.

Try it 5 examples

std::ranges::sort over a whole range

C++intro
0ms
1 2 3 5 8 91 2 3 -4 -7
Reference Β· output compiled offline, not runnable in-browser

The first line is the plain ascending sort; the second sorts by the projection std::abs(x), so -4 and -7 land last by magnitude (keys 4 and 7) even though they are the smallest by value. The projection replaces a hand-written comparator while still sorting the original elements.