Create Views into Containers with Ranges
Learn to create views into containers with ranges.
We'll cover the following
The new ranges library is one of the more significant additions to C++20. It provides a new paradigm for filtering and processing containers. Ranges provide clean and intuitive building blocks for more effective and readable code.
Let's start by defining a few terms:
A range is a collection of objects which can be iterated. In other words, any structure that supports the
begin()
andend()
iterators is a range. This includes most STL containers.A view is a range that transforms another underlying range. Views are lazy, meaning they only operate as the range iterates. A view returns data from the underlying range and does not own any data itself. Views operate in O(1) constant time.
A view adapter is an object that takes a range and returns a view object. A view adapter may be chained with other view adapters using the
|
operator.
Note: The
<ranges>
library uses thestd::ranges
and thestd::ranges::view
namespaces. Recognizing that this is cumbersome, the standard includes an alias forstd::ranges::view
as the simply,std::view
. This is still fairly cumbersome. For this recipe we will use the following aliases, to save space and because it is somewhat more elegant:
namespace ranges = std::ranges; // save the fingers!
namespace views = std::ranges::views;
This applies to all the code in this recipe.
How to do it
The ranges
and views
classes are in the <ranges>
header. Let's look at how we can use them:
A view is applied to a range, like this:
Get hands-on with 1400+ tech skills courses.