# Ranges and views

> A range is anything you can call ranges::begin and ranges::end on; a view is a range cheap enough to pass by value and compose lazily. Views compute on demand, may cache, and refer to data they usually do not own, which explains both their power and their sharp edges.

- **Source:** C++ Atlas (https://cppatlas.com/topics/ranges-and-views)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [range.range] (https://eel.is/c++draft/range.range), [range.sized] (https://eel.is/c++draft/range.sized), [range.view] (https://eel.is/c++draft/range.view), [range.refinements] (https://eel.is/c++draft/range.refinements), [range.all] (https://eel.is/c++draft/range.all), [range.ref.view] (https://eel.is/c++draft/range.ref.view), [range.owning.view] (https://eel.is/c++draft/range.owning.view), [range.filter.view] (https://eel.is/c++draft/range.filter.view), [range.utility.conv.to] (https://eel.is/c++draft/range.utility.conv.to), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged)
- **cppreference links:** [Ranges library](https://en.cppreference.com/w/cpp/ranges), [std::ranges::view](https://en.cppreference.com/w/cpp/ranges/view), [std::views::all](https://en.cppreference.com/w/cpp/ranges/all_view), [std::ranges::owning_view](https://en.cppreference.com/w/cpp/ranges/owning_view), [std::ranges::filter_view](https://en.cppreference.com/w/cpp/ranges/filter_view), [std::ranges::to](https://en.cppreference.com/w/cpp/ranges/to)
- **Prerequisites:** iterator-categories-and-concepts, concepts-and-constraints, algorithms

## The one idea

A **range** is an object you can ask for a beginning and an end. A **view** is a range with one extra promise: moving it, destroying it, and copying it if it is copyable are cheap, independent of how many elements it presents. That promise is what lets views be passed by value, stored inside other views, and stacked into pipelines without anyone worrying about cost.

Most views do not hold elements. They hold a way to reach elements, such as a reference to a container plus a function, and they do their work only when you iterate.

> **Mental model.** A container is a warehouse. A view is a set of directions to the warehouse, with instructions for what to do with each item you find. Directions are cheap to copy, they do nothing until followed, and they lead nowhere once the warehouse is gone.

## The range concept family

`std::ranges::range<R>` requires that `std::ranges::begin` and `std::ranges::end` work on an lvalue of type `R`. The two may return different types: the end is a **sentinel**, which only has to be comparable with the iterator. Semantically, both calls must be amortized constant time, which matters for the caching discussed below.

Refinements add one property each:

| Concept | Adds |
| --- | --- |
| `input_range` through `contiguous_range` | the iterator models the matching iterator concept |
| `sized_range` | `ranges::size(r)` works in amortized constant time |
| `common_range` | iterator and sentinel have the same type |
| `borrowed_range` | iterators stay valid after the range object dies |
| `view` | cheap move and destruction, opted in through `enable_view` |
| `viewable_range` | can be safely converted to a view with `views::all` |
| `constant_range` (C++23) | elements cannot be modified through the iterators |

The associated types follow the iterator ones: `std::ranges::iterator_t<R>`, `sentinel_t<R>`, `range_value_t<R>`, `range_reference_t<R>`, and `range_size_t<R>`.

Not every view is sized or common. `views::iota(0)` has no end value, so its sentinel is a distinct type and it is not common. `views::filter` cannot know how many elements pass without looking, so `ranges::size` on it does not compile.

## What makes a view

The `view` concept is `range<T> && movable<T> && enable_view<T>`. The syntactic part is cheap; the meaning lives in the semantic requirements. A type models `view` only if move construction is constant time, copy construction, when available, is constant time, copy assignment costs no more than destroying and copy-constructing, and destroying N copies or moved-from copies of a view over M elements costs O(N + M).

Opting in is done by deriving from `std::ranges::view_interface<D>`, which also supplies `empty()`, `front()`, `operator[]` and similar helpers, or from `std::ranges::view_base`, or by specializing `enable_view`. The standard specializes it for `std::string_view` and `std::span`. A `std::vector` is a range but not a view, because copying it copies every element.

```cpp
#include <ranges>
#include <span>
#include <string_view>
#include <vector>

static_assert(std::ranges::view<std::string_view>);
static_assert(std::ranges::view<std::span<int>>);
static_assert(!std::ranges::view<std::vector<int>>);   // copying is O(n)
```

The rules were loosened after C++20 shipped, by papers applied as defect reports to C++20 itself. P2325R3 removed the requirement that views be default-constructible. P2415R2 replaced "destruction is constant time" with the O(N + M) rule above, which allows a view to own its elements as long as it cannot be copied. That made `std::ranges::owning_view` possible: a move-only view that holds a container by value.

> **Standardese.** [range.view] states the complexity requirements as semantic constraints. A type can satisfy `view` syntactically and still fail to model it. By [res.on.requirements], a program that relies on a concept being modeled when it is only satisfied is ill-formed, no diagnostic required, so the compiler will not save you.

## `views::all`, `ref_view` and `owning_view`

Every range adaptor starts by turning its input into a view with `views::all`. The rule has three steps:

1. If the argument, decayed, is already a view, copy or move it.
2. Otherwise, if it is an lvalue, wrap it in `std::ranges::ref_view`, which stores a pointer to the range.
3. Otherwise, it is an rvalue container, so move it into an `std::ranges::owning_view`.

```cpp
#include <ranges>
#include <string_view>
#include <type_traits>
#include <vector>

std::vector<int> v{1, 2, 3};
using A = decltype(std::views::all(v));
using B = decltype(std::views::all(std::vector<int>{}));
using C = decltype(std::views::all(std::string_view{}));

static_assert(std::is_same_v<A, std::ranges::ref_view<std::vector<int>>>);
static_assert(std::is_same_v<B, std::ranges::owning_view<std::vector<int>>>);
static_assert(std::is_same_v<C, std::string_view>);
```

This is the meaning of `viewable_range`: a range that `views::all` accepts. Before P2415, step three did not exist, and piping a temporary vector into an adaptor was ill-formed. The lifetime consequences of all three cases belong to the topic on borrowed ranges and dangling.

## Lazy evaluation

Building a pipeline evaluates nothing. Each dereference of a `views::transform` iterator calls the function again, and a `views::filter` iterator evaluates its predicate as it advances. Iterating the same view twice repeats the work.

The combination of the two is a classic surprise. With `transform` before `filter`, the filter's predicate dereferences the underlying transform iterator, and then your loop dereferences it again, so every element that passes is transformed twice.

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

void demo() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x; })
             | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d\n", calls);   // 6: four predicate checks, two loop derefs
}
```

If the transformation is expensive, put the filter first, or materialize the transformed values once.

## Const iteration and caching

The `range` concept requires `begin()` to be amortized constant time. `filter_view` cannot find its first matching element in constant time, so it finds it once, caches the iterator inside the view, and returns the cached value from then on. `drop_while_view` does the same, and so does `drop_view` over a range that is not random-access and sized.

Caching mutates the view, so these views provide only a non-`const` `begin()`. A `const filter_view` is not a range at all.

```cpp
#include <ranges>
#include <vector>

void show(const auto& r) {
  for (int x : r) (void)x;
}

void demo(std::vector<int>& v) {
  auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
  // show(evens);   // ill-formed: filter_view has no const begin()
  for (int x : evens) (void)x;   // fine on a non-const view
}
```

Generic functions that accept views should therefore take them by value or by forwarding reference, not by `const&`. Two consequences of the cache are easy to miss. First, iterating a filtered view a second time skips the search for the first element, so a predicate with side effects runs fewer times on the second pass. Second, the cache is a stored iterator into the underlying range. If you insert into the vector after the first iteration, reallocation invalidates the cached iterator, and iterating the view again is undefined behavior.

> **Pitfall.** A view never sees operations on the range it refers to. Any container operation that invalidates iterators also invalidates the iterators inside a view of that container, including cached ones, so rebuild the view after modifying the container.

`filter_view` adds one more rule: you may modify elements through its iterators, but if an element no longer satisfies the predicate, the behaviour is undefined, because the view's invariant is broken.

## `ranges::to` and range-based `for`

Views produce elements but do not store them. C++23 adds `std::ranges::to` to materialize any range into a container. Given a class template, it deduces the element type; given a complete type, it converts each element.

```cpp
#include <list>
#include <ranges>
#include <vector>

void demo() {
  auto v = std::views::iota(1, 4) | std::ranges::to<std::vector>();  // std::vector<int>
  auto l = v | std::views::filter([](int x) { return x > 1; })
             | std::ranges::to<std::list<long>>();                   // 2, 3 as long
}
```

`ranges::to` tries, in order, direct construction from the range, a constructor taking the `std::from_range` tag, a constructor taking an iterator pair, and finally default construction followed by appending each element.

Range-based `for` predates ranges and does not use `std::ranges::begin`. It binds the range to `auto&& __range`, and calls member `begin()` and `end()` if the class has both, or otherwise unqualified `begin` and `end` found by argument-dependent lookup. Since C++17 the two results may have different types, which is what lets a non-common view be used in a loop. Because `__range` is a non-`const` reference to the view, a filtered view works in a loop even though it is not const-iterable.

## What to remember

- A range needs `ranges::begin` and `ranges::end`; the end can be a sentinel of a different type.
- A view is a range with constant-time move and destruction proportional to its elements, opted in through `enable_view`.
- `std::vector` is not a view; `std::string_view`, `std::span` and adaptor results are.
- C++20 defect reports dropped default construction (P2325) and allowed move-only owning views (P2415).
- `views::all` passes views through, wraps lvalues in `ref_view`, and moves rvalues into `owning_view`.
- Views are lazy and recompute on every pass; `transform` before `filter` calls the function twice per kept element.
- `filter_view` and other caching views are not const-iterable; take views by value or `auto&&`.
- Modifying the underlying container can invalidate a view's cached iterators.
- C++23 `ranges::to` turns a range into a container.

## Concept Map Outline

- **Ranges and views:** A range has begin and end; a view is a range cheap to move and destroy, composed lazily.
  - **Range concepts:** range needs ranges::begin and ranges::end in amortized constant time.
    - **Sentinels:** The end may have a different type from the iterator; common_range means they match.
    - **sized_range:** ranges::size in amortized O(1); filter_view is not sized.
    - **viewable_range:** A range that views::all can safely turn into a view.
    - **constant_range:** C++23: elements cannot be modified through the range's iterators.
  - **What makes a view:** range, movable and enable_view, plus semantic complexity rules.
    - **Cheap operations:** O(1) move, O(1) copy if copyable, destruction O(N+M) over N copies.
    - **Opting in:** Derive from view_interface or view_base, or specialize enable_view.
    - **C++20 defect reports:** P2325 dropped default construction; P2415 allowed move-only owning views.
    - **Not a view:** std::vector is a range but copying it is O(n), so enable_view is false.
  - **views::all:** Every adaptor converts its input with views::all first.
    - **Views pass through:** An argument that is already a view is copied or moved.
    - **ref_view:** Lvalue ranges are wrapped by pointer; the container must outlive the view.
    - **owning_view:** Rvalue containers are moved in; the result is move-only.
  - **Lazy evaluation:** Building a pipeline computes nothing; work happens on iteration.
    - **Recomputed each pass:** transform calls its function on every dereference, every time.
    - **transform then filter:** Kept elements are transformed twice: once by the predicate, once by the loop.
  - **Caching and const:** Views that cannot find begin in O(1) compute it once and store it.
    - **Not const-iterable:** filter, drop_while and some drop views lack a const begin().
    - **Take by value:** Generic code should accept views by value or auto&&, not const&.
    - **Stale caches:** Container operations that invalidate iterators also invalidate cached ones.
    - **filter invariant:** Writing a value that fails the predicate through filter_view is UB.
  - **Materializing and looping:** Views store no elements; containers and loops consume them.
    - **ranges::to:** C++23: builds a container, deducing the element type from a template.
    - **Range-based for:** Uses member or ADL begin and end, not ranges::begin; types may differ since C++17.

## Standardese Quiz Questions

### Question 1 [warmup] ([range.view], [range.ref.view])

In C++23, which of these `static_assert`s fails?

```cpp
#include <ranges>
#include <span>
#include <string_view>
#include <vector>

static_assert(std::ranges::view<std::string_view>);                        // A
static_assert(std::ranges::view<std::span<int>>);                          // B
static_assert(std::ranges::view<std::vector<int>>);                        // C
static_assert(std::ranges::view<std::ranges::ref_view<std::vector<int>>>); // D
```

A. A
B. B
C. D
D. C

**Answer (D):** C

**Why:** A `static_assert` on a false condition makes the program ill-formed, so line C fails to compile. A view must be cheap to copy if it is copyable, and copying a `std::vector` copies every element, so `enable_view<std::vector<int>>` is `false`. The standard specializes `enable_view` for `basic_string_view` and `span`, and `ref_view` derives from `view_interface`, which opts it in. `ref_view` is a view because it only stores a pointer to the vector.

### Question 2 [warmup] ([range.transform.view])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x * x; });
  std::printf("%d ", calls);
  int y = r[2];
  std::printf("%d %d\n", calls, y);
}
```

A. `0 1 9`
B. `4 4 9`
C. `4 5 9`
D. `0 4 9`

**Answer (A):** `0 1 9`

**Why:** Building a view evaluates nothing: `r` stores a `ref_view` of `v` and the lambda, so `calls` is still 0. `r[2]` advances the iterator by 2, which does not call the function, and then dereferences once, so exactly one call computes `3 * 3`. The tempting `4` answers assume the adaptor transforms the whole vector up front, which is how an eager `std::transform` into a new container behaves.

### Question 3 [warmup] ([range.all.general], [range.owning.view])

In C++23, what is the type of `views::all(std::vector<int>{1, 2})`?

A. `std::ranges::ref_view<std::vector<int>>`
B. `std::ranges::owning_view<std::vector<int>>`
C. `std::vector<int>`
D. It is ill-formed: an rvalue container cannot be turned into a view

**Answer (B):** `std::ranges::owning_view<std::vector<int>>`

**Why:** `views::all` copies an argument that is already a view, wraps an lvalue in `ref_view`, and moves any other rvalue range into an `owning_view`. A `ref_view` of a temporary would dangle immediately, which is why it is not chosen. The ill-formed answer describes C++20 as originally published; P2415R2 added `owning_view` and was applied to C++20 as a defect report.

### Question 4 [tricky] ([range.filter.view], [range.filter.iterator], [range.transform.iterator])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x; })
             | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d ", calls);
  calls = 0;
  for (int x : r) (void)x;
  std::printf("%d\n", calls);
}
```

A. `4 4`
B. `6 6`
C. `6 4`
D. `4 2`

**Answer (C):** `6 4`

**Why:** The filter checks each element by dereferencing the transform iterator, which costs four calls, and the loop dereferences each of the two kept elements again, for six. On the second loop, `filter_view::begin()` returns the iterator it cached the first time, so the search that examined `1` and `2` is skipped; the remaining calls are `2` dereferenced in the loop, `3` and `4` checked, and `4` dereferenced, which is four. `6 6` is the answer if you forget the cache.

### Question 5 [tricky] ([range.filter.view], [range.range], [stmt.ranged])

Is this program well-formed?

```cpp
#include <ranges>
#include <vector>

void show(const auto& r) {
  for (int x : r) (void)x;
}

int main() {
  std::vector<int> v{1, 2, 3, 4};
  show(v | std::views::filter([](int x) { return x % 2 == 0; }));
}
```

A. Yes: a `const&` parameter binds to the temporary view
B. Ill-formed: `filter_view` has no `const`-qualified `begin()`
C. Ill-formed: a view cannot bind to a reference parameter
D. Undefined behavior: the view is a temporary

**Answer (B):** Ill-formed: `filter_view` has no `const`-qualified `begin()`

**Why:** `filter_view::begin()` must cache the first matching iterator to meet the amortized constant-time requirement of `range`, so it is a non-`const` member and `const filter_view` does not model `range`. The range-based `for` on `const auto&` therefore finds no usable `begin`. The binding itself is fine, and the temporary lives until the end of the full-expression, so the other answers are wrong; take views by value or by `auto&&`.

### Question 6 [tricky] ([range.prim.size], [range.sized], [range.filter.view])

What happens with `std::ranges::size(f)`?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto f = v | std::views::filter([](int x) { return x > 1; });
  auto n = std::ranges::size(f);
  (void)n;
}
```

A. It returns 3, counting matches in linear time
B. It returns 4, the size of the underlying vector
C. Undefined behavior, because `size` was called before iterating
D. The program is ill-formed: `filter_view` is not a `sized_range`

**Answer (D):** The program is ill-formed: `filter_view` is not a `sized_range`

**Why:** `ranges::size` only works when the size is available in amortized constant time: through a `size()` member or free function, or by subtracting a sized sentinel from the iterator. `filter_view` has neither, because its size depends on how many elements pass the predicate, so the call does not compile. Use `std::ranges::distance(f)`, which is allowed to walk the range and returns 3 here.

### Question 7 [standardese] ([range.filter.iterator])

What does the standard say about this loop?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
  for (int& x : evens) x += 1;
}
```

A. It is well-defined; `v` becomes `1 3 3 5`
B. It is ill-formed: `filter_view` iterators are read-only
C. It is undefined behavior, because the modified elements no longer satisfy the predicate
D. It is well-defined, but iterating `evens` again visits no elements

**Answer (C):** It is undefined behavior, because the modified elements no longer satisfy the predicate

**Why:** [range.filter.iterator] permits modifying the element a `filter_view` iterator denotes, but says the behavior is undefined if the new value does not satisfy the predicate. Adding 1 to an even number makes it odd, so the loop breaks the view's invariant. The iterators do yield `int&`, so the code compiles, and observing `1 3 3 5` on a real implementation does not make it defined. Writing a value that stays even would be fine.

### Question 8 [standardese] ([range.view])

Which of these is **not** a requirement of the `std::ranges::view` concept in C++23?

A. The type is `std::movable`
B. Move construction is constant time
C. The type is default-initializable
D. `std::ranges::enable_view<T>` is `true`

**Answer (C):** The type is default-initializable

**Why:** `view<T>` is `range<T> && movable<T> && enable_view<T>`, with semantic requirements that move construction is constant time and that copies and destruction are cheap. C++20 as published also required `default_initializable`, but P2325R3 removed it and was applied to C++20 as a defect report, so a view such as `ref_view` need not have a default constructor. The other three options are all still required.
