Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ranges::input_range — a readable range

std::ranges::input_range describes a range whose iterator supports reading elements and advancing to subsequent positions. It does not guarantee multiple passes: reading may consume data, as with a stream view.

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

Syntax

#include <ranges>

template<class T>
concept input_range = std::ranges::range<T> &&
                      std::input_iterator<std::ranges::iterator_t<T>>;

// Usage:
template<std::ranges::input_range R>
void consume(R&& r);

std::ranges::input_range<T> is a concept from <ranges>. Its definition combines std::ranges::range<T> with std::input_iterator<std::ranges::iterator_t<T>>. The range supplies a begin iterator and an end sentinel, and its iterator supports reading and incrementing. This is a compile-time type constraint, not a container or a read operation.

Do not assume that traversal can be repeated or that saved iterator positions are independent. An input range may be single-pass; calling begin again need not reproduce the starting position. The stronger std::ranges::forward_range provides the multi-pass guarantee. std::ranges::input_range also does not require the iterator and sentinel to have identical types — that requirement is expressed by std::ranges::common_range.

Readability implies neither immutable elements nor permission to write them. The concept also requires neither a known size nor contiguous storage. Use it to constrain a template when an algorithm needs reading during one traversal; additional operations on elements may need separate constraints.

The example uses std::views::istream<int> over an in-memory stream. The assertions demonstrate an input range that is not a forward range. The loop reads the numbers from the stream and adds them to the running total. The statement after the loop prints the total once: 60 followed by a newline. Do not perform a preliminary traversal merely to count elements before processing them.

Examples

#include <iostream>
#include <locale>
#include <ranges>
#include <sstream>

int main() {
    std::istringstream stream{"10 20 30"};
    stream.imbue(std::locale::classic());
    auto numbers = std::views::istream<int>(stream);

    static_assert(std::ranges::input_range<decltype(numbers)>);
    static_assert(!std::ranges::forward_range<decltype(numbers)>);

    int total = 0;
    for (int value : numbers) {
        total += value;
    }
    std::cout << total << '\n';
}

Result

60

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