Ranges (C++20)
Ranges are a new element of the STL that makes using algorithms more concise and adds the ability to write code in a functional style.
[...]
Terminology
A Range
A range is a type with an iterator pair consisting of a begin()
and end()
function:
struct Range { T begin(); T end(); };
The code above models a classical STL container. For at least some ranges, we need something more general that does not only model a finite range. We usually compare begin and end for equality and stop the iterations as soon as that condition is true. For an infinite range, which is possible with ranges, end is usually a different type than that for begin. The STL brings us a new type for convenience: std::default_sentinel_t
:
struct Range { T begin(); std::default_sentinel_t end(); };
You can see std::default_sentinel_t
as a tag type, which simply enables end()
to have a return type and match the correct overload of operator==
later on.
A common_range
Ranges, as explained, consist of an end()
member function that provides a sentinel. A common_range
, on the other hand, is a range where begin(r)
and end(r)
return the same type. This implies that a common_range
's end()
does not return a sentinel.
All classic iterators model a common_range
. Moreover, most STL types have a common_range constructor.