CKTIS / C++
std::views::keys — a view of first elements
std::views::keys creates a lazy view of the index-0 elements in a range of pairs or tuples. It lets you traverse map keys, but also works with other compatible ranges without creating a separate collection of keys.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <ranges>
std::views::keys(range)
range | std::views::keysstd::views::keys, provided by <ranges>, is a range adaptor equivalent to std::views::elements<0>. Writing range | std::views::keys means the same as std::views::keys(range). It selects the component at index 0 from each element of a compatible range of pairs or tuples; it is not restricted to maps.
The view is lazy: it exposes the selected component when an iterator is dereferenced instead of building a result collection. It preserves the underlying range's order and duplicates—it neither sorts nor deduplicates. std::ranges::keys_view<R> is a type alias for std::ranges::elements_view<R, 0>, not the adaptor's name.
For a range yielding references to pairs, the view can also yield references. The first component of a mutable pair can then be changed, whereas std::map keys are const. A view created from an lvalue container refers to that container: the container must remain alive, and operations that invalidate its iterators can invalidate the view's iterators.
The example prints 3, 1, 3 on separate lines, demonstrating preserved order and duplicates. The displayed code was run unchanged in an isolated environment, and its standard output exactly matched the stated result. For local verification, use -std=c++23. The source is the evolving working draft, not a frozen C++23 publication.
Examples
#include <array>
#include <iostream>
#include <ranges>
#include <utility>
int main() {
std::array<std::pair<int, int>, 3> entries{{
{3, 30}, {1, 10}, {3, 99}
}};
auto keys = entries | std::views::keys;
for (const auto& key : keys) {
std::cout << key << '\n';
}
}
Result
3 1 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.