CKTIS / C++
std::views::reverse — a range viewed in reverse order
std::views::reverse exposes a range's elements from last to first without rearranging the source. It requires a range that can be converted into a bidirectional view. If the view exposes mutable references, writing through them changes the original elements.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <ranges>
std::views::reverse(range)
range | std::views::reversestd::views::reverse, declared in <ranges>, is a range adaptor. The expressions std::views::reverse(range) and range | std::views::reverse let you visit the same elements in reverse order. Adaptation neither rearranges the elements nor creates a reversed copy of them.
The argument must be convertible into a view satisfying std::ranges::bidirectional_range: its iterators must also support moving backward. An input-only or forward-only range is insufficient. The usual result is std::ranges::reverse_view; applying the adaptor to an existing reverse_view returns its underlying range instead of adding another layer.
A view does not imply immutability. In the example, int& allows the elements of values to be modified while traversing backward. Reading through the view afterward yields 30, 20, 10, while values.front() still denotes the source's first element, now equal to 10.
The view created from values refers to that array: do not use it after the array's lifetime ends. Operations that invalidate the source's iterators can also prevent safe use of the view. Not every view is non-owning, however—ownership depends on the underlying range.
Examples
#include <array>
#include <iostream>
#include <ranges>
int main() {
std::array<int, 3> values{1, 2, 3};
auto reversed = values | std::views::reverse;
for (int& value : reversed) {
value *= 10;
}
for (int value : reversed) {
std::cout << value << '\n';
}
std::cout << "first=" << values.front() << '\n';
}
Result
30 20 10 first=10
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.