Ranges library
A guide to Clause 25: a range is an iterator plus a sentinel, customization point objects such as ranges::begin provide access, a family of concepts describes capabilities, and views and adaptors compose lazily. The recurring themes are lazy evaluation, begin() caching and dangling.
Key points
- A range is not a base class but a concept: a type from which
ranges::beginyields an iterator andranges::endyields a sentinel. The sentinel only has to be comparable with the iterator; its type can differ. ranges::begin,ranges::sizeand friends are customization point objects: they look for an implementation in a fixed order and check the result type.- A view is a range that is cheap to copy and move; adaptors return views without computing anything, and elements are computed one at a time during iteration.
- Views usually do not own their elements. The standard blocks some dangling with
dangling,owning_viewand similar tools, but a stored view can still dangle or give stale results. - The libc++ we test with still lacks
views::as_const,views::chunk,views::slide,<generator>and more; the affected examples are marked on each page.
The problem the ranges library solves#
The C++98 algorithm interface is a pair of iterators, e.g. std::sort(v.begin(), v.end()). This has three problems:
- The two iterators can come from different containers, and the compiler cannot tell;
- The begin and end must have the same type, so to express "until
'\0'" or an infinite sequence you must first count the length or fabricate a fake end iterator; - Nothing composes: to filter, then transform, then take the first 3, you either write a loop by hand or build intermediate containers.
The C++20 ranges library (P0896R4) answers all three:
#include <cstdio>
#include <ranges>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8};
auto r = v | std::views::filter([](int x) { return x % 2 == 0; })
| std::views::transform([](int x) { return x * x; })
| std::views::take(3);
for (int x : r) std::printf("%d ", x); // 4 16 36
std::puts("");
}The line that constructs r accesses no element. Each step of the for loop, take asks transform for an element, transform asks filter for one, and filter advances over v until it meets an even number.
This clause forms one whole with the iterators library of Clause 24 ([iterators], [iterator.concepts]) and the std::ranges:: algorithms of Clause 26: the iterator concepts say how you can move, this clause says what a traversable sequence is, and the algorithms put both to use.
Structure of the clause [ranges.general]#
¶1–¶2 This clause describes components for dealing with ranges of elements; Table 84 divides them into six subclauses. Ordered by level of abstraction:
| Level | Subclause | Contents |
|---|---|---|
| Access | [range.access] | customization point objects ranges::begin, end, size, data, empty, etc. |
| Requirements | [range.req] | concepts such as range, sized_range, view, borrowed_range |
| Utilities | [range.utility] | view_interface, subrange, dangling, ranges::to |
| Sources | [range.factories] | views made from nothing: empty, single, iota, repeat, istream |
| Composition | <a class="xref std local" href="../../en/std/range.adaptors.html" data-tip="25.7 Range adaptors — How range adaptors are called and composed: the exact meaning of the pipe operator | , partial application such as views::filter(pred), joining pipelines with your own adaptors via range_adaptor_closure; the pattern shared by all views, and the two helper components movable-box and non-propagating-cache.">[range.adaptors] |
| Coroutines | [coro.generator] | std::generator, an input range written as a coroutine, in <generator> |
Except for the last, all these components are in <ranges>.
The core abstraction: iterator plus sentinel#
range is a concept ([range.range]):
template<class T>
concept range = requires(T& t) {
ranges::begin(t);
ranges::end(t);
};ranges::begin yields an iterator and ranges::end yields a sentinel. The sentinel only needs to be equality-comparable with the iterator, and its type can differ from the iterator's ([iterator.concept.sentinel]). This solves problem 2 above: the end of a C string can be an empty class that checks *p == '\0' when compared with a char*; the end of an infinite sequence can be unreachable_sentinel_t, which compares unequal to every iterator.
On top of this, a chain of refining concepts describes what a range can do. input_range, forward_range, bidirectional_range, random_access_range and contiguous_range get progressively stronger, matching iterator strength. A few others are orthogonal: a sized_range can compute its length in constant time, a common_range has the same type for begin and end, a borrowed_range's iterators do not become invalid together with the range object, and a view is cheap to copy and move. See [range.req].
Three design threads#
Customization point objects#
ranges::begin(r) is not a function but a customization point object (customization point object): a function object that tries arrays, a member begin(), and a begin() found by argument-dependent lookup in a fixed order, and checks that the result is an iterator ([range.access]).
Generic C++17 code had to write the two-step using std::begin; begin(x);, and forgetting the using broke arrays. A customization point object keeps the selection logic in one place, so whether a type is a range can be decided precisely by a concept, and a failure just means the concept is not satisfied rather than a hard error.
Views: lazy, cheap, composable#
A view is a range whose move is constant time and whose destruction cost does not depend on the number of elements ([range.view]), such as string_view, span, and the result of every adaptor. An adaptor ([range.adaptors]) takes a range and returns a view, doing no computation itself. The pipe | in the example above chains such adaptors together.
Lifetime: borrowing and dangling#
Views usually do not own their elements, and a view outliving the underlying data is the most common kind of bug in this clause. The standard has three layers of protection at the type level:
- For an rvalue non-borrowed range, algorithms return
ranges::danglinginstead of an iterator that would dangle ([range.dangling]); views::allproduces aref_viewreferring to an lvalue, and anowning_viewfor an rvalue container, moving the container into the view ([range.all]);viewable_rangerejects things that cannot safely be turned into a view, such as a const rvalue container.
These only catch errors within a single expression. Storing a view, returning it from a function, or continuing to use it after modifying the underlying container can still dangle or invalidate it. The individual view pages keep coming back to this.
Caching begin()#
[range.range]/2 requires ranges::begin to be amortized constant time. filter_view needs a linear search to find its first element, so the standard has it cache the result on the first call to begin(). drop_view, drop_while_view, reverse_view, split_view, chunk_by_view and slide_view do the same in some cases. The caching has two surprising consequences:
begin()on these views is generally not a const member function, because it writes the cache. So when the underlying range is a forward range, a constfilter_viewis not arange, andvoid f(const auto& r)cannot accept it;- After the first call to
begin(), modifying the underlying data can make the view give stale results.
See [range.filter] and [range.drop].
#include <ranges>
#include <span>
#include <vector>
using std::ranges::borrowed_range;
static_assert(borrowed_range<std::span<int>>);
static_assert(borrowed_range<std::ranges::iota_view<int, int>>);
static_assert(!borrowed_range<std::vector<int>>);
using F = decltype(std::declval<std::vector<int>&>()
| std::views::filter([](int) { return true; }));
// filter_view's iterator points back to the view itself (it needs the predicate stored there)
static_assert(!borrowed_range<F>);
static_assert(!std::ranges::range<const F>); // begin() is not a const member
int main() {}
Header <ranges> [ranges.syn]#
A few things in the synopsis are worth noting:
- Mostly available in freestanding implementations. The synopsis begins with the mark mostly freestanding.
basic_istream_view,views::istreamandelements_ofare marked hosted;view_interfaceis partially freestanding because itsat()throwsout_of_range. - Customization point objects live in
inline namespace unspecified. Variables such asranges::beginmay have the same name as hidden friends of view iterators (e.g.iter_move); the inline namespace avoids the conflict of a variable and a function with the same name in one namespace. See [customization.point.object] for the rationale. - Which views are borrowed ranges. The synopsis specializes
enable_borrowed_rangeone by one:subrange,empty_view,iota_viewandref_vieware always borrowed ranges;owning_view,take_view,drop_view,common_view,reverse_view,elements_view,zip_viewand others depend on the underlying view. Those not on the list, such asfilter_viewandtransform_view, are not borrowed ranges, because their iterators have to go back into the view object to get the predicate or function. - Signed and unsigned versions of integer-class types. ¶1 defines
make-unsigned-like-t<X>andto-unsigned-like(x), and ¶2 definesmake-signed-like-t<X>: whenXis an integer type they are justmake_unsigned_tandmake_signed_t; whenXis an integer-class type (a class type that behaves like an integer, [iterator.concept.winc]) they are the corresponding type of the same width.ranges::sizereturning unsigned andranges::ssizereturning signed are defined in terms of them. from_range_tandfrom_range. The tag used since C++23 when constructing a container from a range (P1206R7);ranges::toprefers it.
Evolution#
History
- C++20 (P0896R4) introduced the concepts, the customization point objects,
subrange,dangling,view_interface, and the basic factories and adaptorsiota,filter,transform,take,drop,join,split,reverse,elementsand others. Several later papers went back and changed C++20 as defect reports; the most important introducedowning_viewand redefined views (P2415R2), so that rvalue containers can go into a pipeline too. - C++23 added
ranges::to(P1206R7), user-defined pipeable adaptors (P2387R3), the adaptorszip,chunk,slide,join_with,enumerate,as_constand others, andstd::generator. - C++26 added
concat,views::indices,cache_latest,as_inputandranges::reserve_hint, and madeoptionala range of at most one element.
Implementation status in our tests#
The examples on this site are checked with Clang 23 and libc++. At the time of writing, libc++ does not yet provide views::as_const, views::chunk, views::slide, views::cartesian_product, views::cache_latest, views::as_input, ranges::reserve_hint or <generator>; ranges::cbegin does not yet return a constant iterator, and optional is not yet a range. Examples involving these facilities are marked on their pages as not run locally.
Reading order#
- [range.access] and [range.req]: how a range is defined precisely by customization point objects and concepts;
- [range.view] and [range.all]: the semantic requirements on views,
ref_viewandowning_view; - [range.adaptors]: the rules for adaptor objects, closure objects and the pipe
|; - Key views: [range.filter], [range.transform], [range.join], [range.split], [range.zip];
- Utilities: [range.subrange], [range.dangling], [range.utility.conv].
Contents
- 25.1General[ranges.general]
- 25.2Header <ranges> synopsis[ranges.syn]
- 25.3Range access[range.access]done
- 25.3.1General[range.access.general]
- 25.3.2ranges::begin[range.access.begin]
- 25.3.3ranges::end[range.access.end]
- 25.3.4ranges::cbegin[range.access.cbegin]
- 25.3.5ranges::cend[range.access.cend]
- 25.3.6ranges::rbegin[range.access.rbegin]
- 25.3.7ranges::rend[range.access.rend]
- 25.3.8ranges::crbegin[range.access.crbegin]
- 25.3.9ranges::crend[range.access.crend]
- 25.3.10ranges::size[range.prim.size]
- 25.3.11ranges::ssize[range.prim.ssize]
- 25.3.12ranges::reserve_hint[range.prim.size.hint]
- 25.3.13ranges::empty[range.prim.empty]
- 25.3.14ranges::data[range.prim.data]
- 25.3.15ranges::cdata[range.prim.cdata]
- 25.4Range requirements[range.req]done
- 25.5Range utilities[range.utility]done
- 25.5.1General[range.utility.general]
- 25.5.2Helper concepts[range.utility.helpers]
- 25.5.3View interface[view.interface]
- 25.5.4Sub-ranges[range.subrange]done
- 25.5.5Dangling iterator handling[range.dangling]done
- 25.5.6Class template elements_of[range.elementsof]
- 25.5.7Range conversions[range.utility.conv]done
- 25.6Range factories[range.factories]done
- 25.7Range adaptors[range.adaptors]done
- 25.7.1General[range.adaptors.general]
- 25.7.2Range adaptor objects[range.adaptor.object]
- 25.7.3Movable wrapper[range.move.wrap]
- 25.7.4Non-propagating cache[range.nonprop.cache]
- 25.7.5Range adaptor helpers[range.adaptor.helpers]
- 25.7.6All view[range.all]done
- 25.7.7As rvalue view[range.as.rvalue]
- 25.7.8Filter view[range.filter]done
- 25.7.9Transform view[range.transform]done
- 25.7.10Take view[range.take]done
- 25.7.11Take while view[range.take.while]
- 25.7.12Drop view[range.drop]done
- 25.7.13Drop while view[range.drop.while]
- 25.7.14Join view[range.join]done
- 25.7.15Join with view[range.join.with]
- 25.7.16Lazy split view[range.lazy.split]
- 25.7.16.1Overview[range.lazy.split.overview]
- 25.7.16.2Class template lazy_split_view[range.lazy.split.view]
- 25.7.16.3Class template lazy_split_view::outer-iterator[range.lazy.split.outer]
- 25.7.16.4Class lazy_split_view::outer-iterator::value_type[range.lazy.split.outer.value]
- 25.7.16.5Class template lazy_split_view::inner-iterator[range.lazy.split.inner]
- 25.7.17Split view[range.split]done
- 25.7.18Concat view[range.concat]done
- 25.7.19Counted view[range.counted]
- 25.7.20Common view[range.common]done
- 25.7.21Reverse view[range.reverse]done
- 25.7.22As const view[range.as.const]done
- 25.7.23Elements view[range.elements]done
- 25.7.24Enumerate view[range.enumerate]done
- 25.7.25Zip view[range.zip]done
- 25.7.26Zip transform view[range.zip.transform]
- 25.7.27Adjacent view[range.adjacent]
- 25.7.28Adjacent transform view[range.adjacent.transform]
- 25.7.28.1Overview[range.adjacent.transform.overview]
- 25.7.28.2Class template adjacent_transform_view[range.adjacent.transform.view]
- 25.7.28.3Class template adjacent_transform_view::iterator[range.adjacent.transform.iterator]
- 25.7.28.4Class template adjacent_transform_view::sentinel[range.adjacent.transform.sentinel]
- 25.7.29Chunk view[range.chunk]done
- 25.7.29.1Overview[range.chunk.overview]
- 25.7.29.2Class template chunk_view for input ranges[range.chunk.view.input]
- 25.7.29.3Class chunk_view::outer-iterator[range.chunk.outer.iter]
- 25.7.29.4Class chunk_view::outer-iterator::value_type[range.chunk.outer.value]
- 25.7.29.5Class chunk_view::inner-iterator[range.chunk.inner.iter]
- 25.7.29.6Class template chunk_view for forward ranges[range.chunk.view.fwd]
- 25.7.29.7Class template chunk_view::iterator for forward ranges[range.chunk.fwd.iter]
- 25.7.30Slide view[range.slide]
- 25.7.31Chunk by view[range.chunk.by]
- 25.7.32Stride view[range.stride]
- 25.7.33Cartesian product view[range.cartesian]draft
- 25.7.34Cache latest view[range.cache.latest]draft
- 25.7.35As input view[range.as.input]
- 25.8Range generators[coro.generator]draft
- 25.8.1Overview[coroutine.generator.overview]
- 25.8.2Header <generator> synopsis[generator.syn]
- 25.8.3Class template generator[coro.generator.class]
- 25.8.4Members[coro.generator.members]
- 25.8.5Class generator::promise_type[coro.generator.promise]
- 25.8.6Class generator::iterator[coro.generator.iterator]