std::ranges::views::keys, std::ranges::keys_view

< cpp‎ | ranges
Defined in header <ranges>
template<class R>
using keys_view = ranges::elements_view<R, 0>;
(1) (since C++20)
namespace views {

    inline constexpr auto keys = ranges::elements<0>;

(2) (since C++20)

Takes a view of tuple-like values (e.g. std::tuple or std::pair), and produces a view with a value-type of the first element of the adapted view's value-type.

1) An alias for ranges::elements_view<R, 0>.
2) Range adaptor object. The expression views::keys(e) is expression-equivalent to keys_view<views::all_t<decltype((e))>>{e} for any suitable subexpression e.


[edit] Expression-equivalent

Expression e is expression-equivalent to expression f, if e and f have the same effects, either are both potentially-throwing or are both not potentially-throwing (i.e. noexcept(e) == noexcept(f)), and either are both constant subexpressions or are both not constant subexpressions.

[edit] Notes

keys_view can be useful for extracting keys from associative containers, e.g. for (auto const& key : std::views::keys(map)) { /*...*/ }.

[edit] Example

#include <iomanip>
#include <iostream>
#include <ranges>
#include <utility>
#include <vector>
#include <string>
int main()
    const std::vector<std::pair<std::string, double>> quark_mass{ // MeV/c²
        {"up", 2.3},      {"down", 4.8},
        {"charm", 1275},  {"strange", 95},
        {"top", 173'210}, {"bottom", 4'180},
    std::cout << "quark name:  │ ";
    for (std::string const& name : std::views::keys(quark_mass))
        std::cout << std::setw(9) << name << " │ ";
    std::cout << "\n" "mass MeV/c²: │ ";
    for (const double mass : std::views::values(quark_mass))
        std::cout << std::setw(9) << mass << " │ ";
    std::cout << '\n';


quark name:  │        up │      down │     charm │   strange │       top │    bottom │ 
mass MeV/c²: │       2.3 │       4.8 │      1275 │        95 │    173210 │      4180 │

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3563 C++20 keys_view is unable to participate in CTAD due to its use of views::all_t views::all_t removed

[edit] See also

takes a view consisting of pair-like values and produces a view of the second elements of each pair
(class template) (range adaptor object) [edit]
takes a view consisting of tuple-like values and a number N and produces a view of N'th element of each tuple
(class template) (range adaptor object) [edit]
BLAS-like slice of a valarray: starting index, length, stride
(class) [edit]