CKTIS / C++
std::views::enumerate — iteration with an index
C++23 std::views::enumerate creates a lazy view that associates each range element with a zero-based index. It lets a loop access both the index and the element without maintaining a separate counter.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::views::enumerate(range)
range | std::views::enumeratestd::views::enumerate, available in <ranges>, is a C++23 range adaptor. Writing std::views::enumerate(range) or range | std::views::enumerate creates a std::ranges::enumerate_view. The view computes results during iteration instead of building a container of pairs.
Dereferencing its iterator produces a std::tuple containing an index and the result of dereferencing the underlying iterator. The index starts at 0 and uses the underlying range's difference type, not necessarily std::size_t. In auto [index, value], value preserves the range's reference or proxy semantics: for a mutable std::array<int, 3>, assigning to value changes the original element despite the use of auto.
The index describes a position in the range passed to the adaptor. If you apply a filter first, numbering refers to the filtered sequence rather than the original positions. When the view refers to an existing container, that container must remain alive; also avoid operations that invalidate the iterators being used.
The example increments the elements and prints their indices. It requires both a compiler and a standard library supporting this adaptor. Repository metadata records a C++23 flag but does not attest the production runtime. The cited document is an evolving working draft, not a frozen C++23 publication.
Examples
#include <array>
#include <iostream>
#include <ranges>
#include <tuple>
int main() {
std::array<int, 3> values{10, 20, 30};
for (auto [index, value] : values | std::views::enumerate) {
value += 1;
std::cout << index << ':' << value << '\n';
}
std::cout << "first=" << values[0] << '\n';
}
Result
0:11 1:21 2:31 first=11
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.