Namespaces
Variants
Views
Actions

Ranges library (C++20)

From cppreference.com
< cpp
Revision as of 10:56, 11 February 2023 by D41D8CD98F (Talk | contribs)

 
 
Ranges library
Range adaptors
 

The ranges library is an extension and generalization of the algorithms and iterator libraries that makes them more powerful by making them composable and less error-prone.

The library creates and manipulates range views, lightweight objects that indirectly represent iterable sequences (ranges). Ranges are an abstraction on top of

  • [begin, end) iterator pairs, e.g. ranges made by implicit conversion from containers. All algorithms that take iterator pairs now have overloads that accept ranges (e.g ranges::sort)
  • [start, size) counted sequences, e.g. range returned by views::counted
  • [start, predicate) conditionally-terminated sequences, e.g. range returned by views::take_while
  • [start..) unbounded sequences, e.g. range returned by views::iota

The ranges library includes range algorithms, which are applied to ranges eagerly, and range adaptors, which are applied to views lazily. Adaptors can be composed into pipelines, so that their actions take place as the view is iterated.

Defined in header <ranges>
namespace std {

    namespace views = ranges::views;

}
(since C++20)

The namespace alias std::views is provided as a shorthand for std::ranges::views.

Defined in namespace std::ranges

Contents

Range access
Defined in header <ranges>
Defined in header <iterator>
returns an iterator to the beginning of a range
(customization point object)[edit]
returns a sentinel indicating the end of a range
(customization point object)[edit]
returns an iterator to the beginning of a read-only range
(customization point object)[edit]
returns a sentinel indicating the end of a read-only range
(customization point object)[edit]
returns a reverse iterator to a range
(customization point object)[edit]
returns a reverse end iterator to a range
(customization point object)[edit]
returns a reverse iterator to a read-only range
(customization point object)[edit]
returns a reverse end iterator to a read-only range
(customization point object)[edit]
returns an integer equal to the size of a range
(customization point object)[edit]
returns a signed integer equal to the size of a range
(customization point object)[edit]
checks whether a range is empty
(customization point object)[edit]
obtains a pointer to the beginning of a contiguous range
(customization point object)[edit]
obtains a pointer to the beginning of a read-only contiguous range
(customization point object)[edit]
Range primitives
Defined in header <ranges>
obtains iterator and sentinel types of a range
(alias template)[edit]
Dangling iterator handling
Defined in header <ranges>
a placeholder type indicating that an iterator or a subrange should not be returned since it would be dangling
(class) [edit]
obtains iterator type or subrange type of a borrowed_range
(alias template)[edit]
Range concepts
Defined in header <ranges>
specifies that a type is a range, that is, it provides a begin iterator and an end sentinel
(concept) [edit]
specifies that a type is a range and iterators obtained from an expression of it can be safely returned without danger of dangling
(concept) [edit]
specifies that a range knows its size in constant time
(concept) [edit]
specifies that a range is a view, that is, it has constant time copy/move/assignment
(concept) [edit]
specifies a range whose iterator type satisfies input_iterator
(concept) [edit]
specifies a range whose iterator type satisfies output_iterator
(concept) [edit]
specifies a range whose iterator type satisfies forward_iterator
(concept) [edit]
specifies a range whose iterator type satisfies bidirectional_iterator
(concept) [edit]
specifies a range whose iterator type satisfies random_access_iterator
(concept) [edit]
specifies a range whose iterator type satisfies contiguous_iterator
(concept) [edit]
specifies that a range has identical iterator and sentinel types
(concept) [edit]
specifies the requirements for a range to be safely convertible to a view
(concept) [edit]
specifies that a range has read-only elements
(concept) [edit]
Range conversions
Defined in header <ranges>
constructs a new non-view object from an input range
(function template) [edit]
Views
Defined in header <ranges>
helper class template for defining a view, using the curiously recurring template pattern
(class template) [edit]
combines an iterator-sentinel pair into a view
(class template) [edit]

Range factories

Defined in header <ranges>
Defined in namespace std::ranges
an empty view with no elements
(class template) (variable template)[edit]
a view that contains a single element of a specified value
(class template) (customization point object)[edit]
a view consisting of a sequence generated by repeatedly incrementing an initial value
(class template) (customization point object)[edit]
a view consisting of the elements obtained by successive application of operator>> on the associated input stream
(class template) (customization point object)[edit]
a view consisting of a generated sequence by repeatedly producing the same value
(class template) (customization point object)[edit]
a view consisting of tuples of results calculated by the n-ary cartesian product of the adapted views
(class template) (customization point object)[edit]

Range adaptors

Defined in header <ranges>
Defined in namespace std::ranges
a view that includes all elements of a range
(alias template) (range adaptor object)[edit]
a view of the elements of some other range
(class template) [edit]
a view with unique ownership of some range
(class template) [edit]
a view that consists of the elements of a range that satisfies a predicate
(class template) (range adaptor object)[edit]
a view of a sequence that applies a transformation function to each element
(class template) (range adaptor object)[edit]
a view consisting of the first N elements of another view
(class template) (range adaptor object)[edit]
a view consisting of the initial elements of another view, until the first element on which a predicate returns false
(class template) (range adaptor object)[edit]
a view consisting of elements of another view, skipping the first N elements
(class template) (range adaptor object)[edit]
a view consisting of the elements of another view, skipping the initial subsequence of elements until the first element where the predicate returns false
(class template) (range adaptor object)[edit]
a view consisting of the sequence obtained from flattening a view of ranges
(class template) (range adaptor object)[edit]
a view over the subranges obtained from splitting another view using a delimiter
(class template) (range adaptor object)[edit]
a view over the subranges obtained from splitting another view using a delimiter
(class template) (range adaptor object)[edit]
creates a subrange from an iterator and a count
(customization point object)[edit]
converts a view into a common_range
(class template) (range adaptor object)[edit]
a view that iterates over the elements of another bidirectional view in reverse order
(class template) (range adaptor object)[edit]
takes a view consisting of tuple-like values and a number N and produces a view of Nth element of each tuple
(class template) (range adaptor object)[edit]
takes a view consisting of pair-like values and produces a view of the first elements of each pair
(class template) (range adaptor object)[edit]
takes a view consisting of pair-like values and produces a view of the second elements of each pair
(class template) (range adaptor object)[edit]
a view consisting of tuples of references to corresponding elements of the adapted views
(class template) (customization point object)[edit]
a view consisting of results of application of a transformation function to corresponding elements of the adapted views
(class template) (customization point object)[edit]
a view consisting of tuples of references to adjacent elements of the adapted view
(class template) (range adaptor object)[edit]
a view consisting of results of application of a transformation function to adjacent elements of the adapted view
(class template) (range adaptor object)[edit]
a view consisting of the sequence obtained from flattening a view of ranges, with the delimiter in between elements
(class template) (range adaptor object)[edit]
a view whose Mth element is a view over the Mth through (M + N - 1)th elements of another view
(class template) (range adaptor object)[edit]
a range of views that are N-sized non-overlapping successive chunks of the elements of another view
(class template) (range adaptor object)[edit]
splits the view into subranges between each pair of adjacent elements for which the given predicate returns false
(class template) (range adaptor object)[edit]
converts a view into a constant_range
(class template) (range adaptor object)[edit]
a view of a sequence that casts each element to an rvalue
(class template) (range adaptor object)[edit]
a view consisting of elements of another view, advancing over N elements at a time
(class template) (range adaptor object)[edit]

Range generators

Defined in header <generator>
Defined in namespace std
(C++23)
A view that represents synchronous coroutine generator
(class template) [edit]


Range adaptor closure objects

Range adaptor closure objects are objects whose type is the same as one of the following objects (ignoring cv-qualification):

  • unary range adaptor objects,
  • objects of user-defined types other than unary range adaptor objects who meet the requirements of implementing a range adaptor closure object,
(since C++23)
  • the results of binding trailing arguments by range adaptor objects, and
  • the results of chaining two range adaptor closure objects by operator|.

Range adaptor closure objects take one viewable_range(until C++23) range(since C++23) as its only argument and returns a view(until C++23). They are callable via the pipe operator: if C is a range adaptor closure object and R is a viewable_range(until C++23) range(since C++23), these two expressions are equivalent (both well-formed or ill-formed):

C(R)
R | C

This call forwards the bound arguments (if any) to the associated range adaptor object. The bound arguments (if any) are identically treated as lvalue or rvalue and cv-qualified to C.

Two range adaptor closure objects can be chained by operator| to produce another range adaptor closure object: if C and D are range adaptor closure objects, then C | D is also a range adaptor closure object if it is valid.

The bound arguments of C | D is determined as follows:

  • there is a subobject in the result object of the same type (cv-qualification discarded) for every subobject in both operands that is a bound argument,
  • such a bound argument is direct-non-list-initialized with the source subobject in its containing operand, where the source is identically treated as lvalue or rvalue and cv-qualified to the operand,
  • the result is valid if and only if the initialization of all bound arguments are valid.

The effect and validity of the operator() of the result is determined as follows: given a viewable_range(until C++23) range(since C++23) R, these two expressions are equivalent (both well-formed or ill-formed):

R | C | D // (R | C) | D
R | (C | D)

Notes: operator() is unsupported for volatile-qualified or const-volatile-qualified version of range adaptor object closure types.

Let t be the object of type T, then t is a range adaptor closure object if all the requirements are met:

One can create a user-defined range adaptor closure object by following the requirements above.

#include <ranges>
#include <algorithm>
 
struct TakeTripleAndReverse 
: std::ranges::range_adaptor_closure<TakeTripleAndReverse> 
{
    template <std::ranges::viewable_range R>
        requires std::ranges::bidirectional_range<R>
    constexpr auto operator()(R&& r) const 
    {
        return std::forward<R>(r) | std::views::take(3)
                                  | std::views::reverse;
    }
};
 
inline constexpr TakeTripleAndReverse take_triple_and_reverse {};
 
template <typename R, typename T>
constexpr bool equal_to(R&& r, std::initializer_list<T> il) 
{
    return std::ranges::equal(r, il);
}
 
int main() 
{
    static constexpr int arr[] = {6, 2, 8, 4, 4, 2};
    static constexpr auto plus_one = std::views::transform([](int n){ return n + 1; });
 
    static_assert(equal_to(take_triple_and_reverse(arr), {8, 2, 6}));
    static_assert(equal_to(arr | take_triple_and_reverse, {8, 2, 6}));
    static_assert(equal_to(arr | take_triple_and_reverse | plus_one, {9, 3, 7}));
    static_assert(equal_to(arr | plus_one | take_triple_and_reverse, {9, 3, 7}));
}
(since C++23)

Range adaptor objects

Range adaptor objects are customization point objects that accept viewable_range as their first arguments and return a view. Some range adaptor objects are unary, i.e. they take one viewable_range as their only argument. Other range adaptor objects take a viewable_range and other trailing arguments.

If a range adaptor object takes more than one argument, it also supports partial application: let

  • a be such a range adaptor object, and
  • args... be arguments (generally suitable for trailing arguments),

expression a(args...) has following properties:

  • it is valid if and only if for every argument e in args... such that E is decltype((e)), std::is_constructible_v<std::decay_t<E>, E> is true,
  • when the call is valid, its result object stores a subobject of type std::decay_t<E> direct-non-list-initialized with std::forward<E>(e), for every argument e in args... (in other words, range adaptor objects bind arguments by value), and
  • the result object is a range adaptor closure object.

Like other customization point objects, let

  • a be an object of the cv-unqualified version of the type of any range adaptor objects,
  • args... be any group of arguments that satisfies the constraints of the operator() of the type of a,

calls to

are all equivalent.

The result object of each of these expressions is either a view object or a range adaptor closure object.

Notes: operator() is unsupported for volatile-qualified or const-volatile-qualified version of range adaptor object types. Arrays and functions are converted to pointers while binding.

Movable wrapper

Some range adaptors wrap their elements or function objects with the movable-wrapper.

Non-propagating cache

Some range adaptors are specified in terms of an exposition-only class template non-propagating-cache, which behaves almost exactly like std::optional<T> (see description for differences).

Range adaptor helpers

<tr class="t-dcl ">

<td >
template< class F, class Tuple >

constexpr auto /*tuple-transform*/( F&& f, Tuple&& tuple ) {    // exposition only
  return std::apply([&]<class... Ts>(Ts&&... elements) {
    return std::tuple<std::invoke_result_t<F&, Ts>...>(
      std::invoke(f, std::forward<Ts>(elements))...
    );
  }, std::forward<Tuple>(tuple));

}
</td>

<td > (1) </td> <td class="t-dcl-nopad"> </td> </tr> <tr class="t-dcl ">

<td >
template< class F, class Tuple >

constexpr void /*tuple-for-each*/( F&& f, Tuple&& tuple ) {    // exposition only
  std::apply([&]<class... Ts>(Ts&&... elements) {
    (static_cast<void>(std::invoke(f, std::forward<Ts>(elements))), ...);
  }, std::forward<Tuple>(tuple));

}
</td>

<td > (2) </td> <td class="t-dcl-nopad"> </td> </tr>

Some range adaptors are specified in terms of these exposition-only function templates.

1) /*tuple-transform*/ returns a new tuple constructed by applying f to each element of tuple.
2) /*tuple-for-each*/ applies f to each element of tuple and returns nothing.

Helper concepts

Following exposition-only concepts are used for several types, but they are not parts of the interface of standard library.

template<class R>

  concept __simple_view =                     // exposition only
    ranges::view<R> && ranges::range<const R> &&
    std::same_as<std::ranges::iterator_t<R>, std::ranges::iterator_t<const R>> &&

    std::same_as<std::ranges::sentinel_t<R>, std::ranges::sentinel_t<const R>>;

Notes

Feature-test macro Value Std Feature
__cpp_lib_generator 202207L (C++23) std::generator – synchronous coroutine generator for ranges
__cpp_lib_ranges 201911L (C++20) Ranges library and constrained algorithms
202106L (C++20)
(DR)
Non-default-initializable views
202110L (C++20)
(DR)
Views with ownership
202202L (C++23) std::ranges::range_adaptor_closure
202207L (C++23) Relaxing range adaptors to allow for move only types
202211L (C++23) Removing "poison pills" overloads in ranges::begin etc
__cpp_lib_ranges_as_const 202207L (C++23) std::const_iterator, std::ranges::as_const_view
__cpp_lib_ranges_as_rvalue 202207L (C++23) std::ranges::as_rvalue_view
__cpp_lib_ranges_cartesian_product 202207L (C++23) std::ranges::cartesian_product_view
__cpp_lib_ranges_chunk 202202L (C++23) std::ranges::chunk_view
__cpp_lib_ranges_chunk_by 202202L (C++23) std::ranges::chunk_by_view
__cpp_lib_ranges_join_with 202202L (C++23) std::ranges::join_with_view
__cpp_lib_ranges_repeat 202207L (C++23) std::ranges::repeat_view
__cpp_lib_ranges_slide 202202L (C++23) std::ranges::slide_view
__cpp_lib_ranges_stride 202207L (C++23) std::ranges::stride_view
__cpp_lib_ranges_to_container 202202L (C++23) std::ranges::to
__cpp_lib_ranges_zip 202110L (C++23) std::ranges::zip_view, std::ranges::zip_transform_view, std::ranges::adjacent_view, std::ranges::adjacent_transform_view

Example

#include <iostream>
#include <ranges>
 
int main()
{
    auto const ints = {0, 1, 2, 3, 4, 5};
    auto even = [](int i) { return 0 == i % 2; };
    auto square = [](int i) { return i * i; };
 
    // the "pipe" syntax of composing the views:
    for (int i : ints | std::views::filter(even) | std::views::transform(square))
        std::cout << i << ' ';
 
    std::cout << '\n';
 
    // a traditional "functional" composing syntax:
    for (int i : std::views::transform(std::views::filter(ints, even), square))
        std::cout << i << ' ';
}

Output:

0 4 16
0 4 16

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3509 C++20 it was unclear how range adaptor objects bound trailing arguments they are bound by value

See also