Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ranges::subrange — an iterator–sentinel view

std::ranges::subrange from <ranges> combines a starting iterator and an ending sentinel into a view of [first, last). It does not copy elements into a new container; it lets you pass a selected portion of data as one object.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <ranges>
std::ranges::subrange r(first, last);
r.begin();
r.end();

std::ranges::subrange<I, S, K> stores an iterator and a sentinel, forming a view of [first, last): the beginning is included, and the end is excluded. Types I and S may differ; storage need not be contiguous. Include <ranges>. Constructing std::ranges::subrange(first, last) lets template argument deduction determine the types.

std::ranges::subrange::begin returns a copy of the stored iterator when I satisfies copyable. Otherwise, only the non-const overload is available, and it moves the stored iterator; do not assume repeated calls will reproduce the same beginning in that case. std::ranges::subrange::end returns a copy of the sentinel. Compare an iterator with end() before dereferencing it; the sentinel itself need not support dereferencing.

K selects subrange_kind::sized or subrange_kind::unsized. Only the sized variant provides size(): it computes the result by subtracting the endpoints or stores a size when that subtraction is unavailable. The constructor taking n requires n to equal the actual length of the valid range [first, last).

The view neither copies elements nor itself extends the lifetime of the data. Do not use it after the data is destroyed or its iterators are invalidated. Modification through a writable iterator changes the original data; making the view itself const does not make its elements constant.

The example covers values[1], values[2], and values[3]. After changing the first of these to 21, it prints exactly sum=91 and values[1]=21, each on its own line. Environment scope: C++23; repository compiler flag, production runtime not attested. The online standard is an evolving draft, not a frozen C++23 publication.

Examples

#include <iostream>
#include <ranges>

int main() {
    int values[] = {10, 20, 30, 40, 50};
    auto middle = std::ranges::subrange(values + 1, values + 4);

    *middle.begin() = 21;
    int sum = 0;
    for (auto it = middle.begin(); it != middle.end(); ++it) {
        sum += *it;
    }

    std::cout << "sum=" << sum << '\n';
    std::cout << "values[1]=" << values[1] << '\n';
}

Result

sum=91
values[1]=21

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources