Modern C++ › C++20
Ranges and Views
Composable, lazy pipelines over sequences.
Since C++20 intermediate #ranges#views#pipelines#lazy-evaluation#projections#algorithms
Explanation
Ranges (<ranges>) rework the STL around a simple idea: a range is anything with begin() and end(). Two big gains:
- Range algorithms in
std::ranges::take the whole container:std::ranges::sort(v)instead ofstd::sort(v.begin(), v.end()). They are constrained by concepts (clear errors) and accept projections:std::ranges::sort(people, {}, &Person::age)sorts by a member. - Views: lightweight, non-owning, lazy range adaptors that are composed with
|. A view does no work until you iterate it, allocates nothing, and does not copy elements.
auto r = v | std::views::filter(isEven) | std::views::transform(square) | std::views::take(3);
Common views: filter, transform, take, drop, take_while, drop_while, reverse, keys, values, elements<N>, split, join, iota (a generator of consecutive numbers), common.
Views are cheap to copy and reflect later changes of the underlying container, because they just refer to it.
Example
#include <algorithm>
#include <iostream>
#include <map>
#include <ranges>
#include <string>
#include <vector>
namespace rv = std::views;
struct Person { std::string name; int age; };
int main() {
std::vector<int> v{5, 3, 8, 1, 9, 2, 7};
std::ranges::sort(v); // whole-container call
std::cout << std::ranges::binary_search(v, 8) << "\n"; // 1
auto evensSquared = v
| rv::filter([](int x) { return x % 2 == 0; })
| rv::transform([](int x) { return x * x; }); // nothing computed yet
for (int x : evensSquared) std::cout << x << " "; // 4 64
std::cout << "\n";
for (int i : rv::iota(1, 6) | rv::reverse) // 5 4 3 2 1
std::cout << i << " ";
std::cout << "\n";
for (int x : rv::iota(1) | rv::take_while([](int n) { return n < 30; })
| rv::filter([](int n) { return n % 7 == 0; })) // infinite source, lazy
std::cout << x << " "; // 7 14 21 28
std::cout << "\n";
std::vector<Person> people{{"Ann", 31}, {"Bob", 25}, {"Cy", 40}};
std::ranges::sort(people, {}, &Person::age); // projection: sort by age
std::cout << people.front().name << "\n"; // Bob
std::map<std::string, int> stock{{"apple", 5}, {"pear", 2}};
for (const auto& k : stock | rv::keys) std::cout << k << " "; // apple pear
std::cout << "\n";
auto it = std::ranges::find(v, 8);
std::cout << (it != v.end() ? "found" : "missing") << "\n";
return 0;
}
Common pitfalls
- Dangling: a view over a temporary container (
getVector() | rv::filter(...)) dangles after the full expression. The range algorithms returnstd::ranges::danglingto stop you from using such an iterator. - Views are lazy: a
transformlambda with side effects runs each time you iterate, andfiltercaches its firstbegin(), so modifying the underlying data after that is undefined. - A
filterview is notconst-iterable; iterate it by non-const reference or by value. - There is no
to<std::vector>()in C++20 to materialize a view: copy into a container by hand (or use C++23’sstd::ranges::to). - Compile times grow with deep view pipelines, and debug builds can be slow.
Legacy vs modern
// C++98..17
std::vector<int> out;
std::remove_copy_if(v.begin(), v.end(), std::back_inserter(out), isOdd);
std::transform(out.begin(), out.end(), out.begin(), square);
// C++20: no intermediate container, lazy
auto out = v | rv::filter(isEven) | rv::transform(square);
See Algorithms and Iterators for what this builds on. C++23 adds ranges::to, zip, enumerate, chunk and more: Ranges Additions in C++23.
Exercises
1. Print the first five odd squares using views.
for (int x : rv::iota(1) | rv::filter([](int n){ return n % 2; })
| rv::transform([](int n){ return n * n; })
| rv::take(5))
std::cout << x << " "; // 1 9 25 49 81