Namespaces
Variants
Views
Actions

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

From cppreference.com
< cpp‎ | ranges
 
 
 
Defined in header <ranges>
template<class R>
using keys_view = ranges::elements_view<views::all_t<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) is an alias for ranges::elements_­view<views​::​all_­t<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.

Contents

[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>
 
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';
}

Output:

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

[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]