Search⌘ K

Exploring More Examples of Range Adaptors

Learn to apply various range adaptors in C++20 and C++23, including filter, transform, reverse, take_view, and join_with. This lesson provides practical examples demonstrating how to manipulate sequences and views effectively, enhancing your ability to write clean and efficient range-based code.

Previously in this section, we saw the following example (this time with explicit namespaces):

C++ 17
namespace rv = std::ranges::views;
std::ranges::sort(v);
auto r = v
| rv::filter([](int const n) {return n % 2 == 0; })
| rv::drop(2)
| rv::reverse
| rv::transform([](int const n) {return n * n; });

This is actually the shorter and more readable version of the following:

C++ 17
std::ranges::sort(v);auto r =
rv::transform(
rv::reverse(
rv::drop(
rv::filter(
v,
[](int const n) {return n % 2 == 0; }),
2)),
[](int const n) {return n * n; });

The first version is possible because the pipe operator (|) is overloaded to simplify the composition of views in a more human-readable form.

Passing arguments to range adaptors

Some range adaptors take one argument, and some may take multiple arguments. The following rules apply:

  • If a range adaptor A takes one argument, a view V, then A(V) ...