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

From cppreference.com
< cpp‎ | ranges
 
 
Ranges library
Range access
Range conversions
(C++23)
Range primitives



Dangling iterator handling
Range concepts
Views

Factories






Adaptors
Range adaptor objects
Range adaptor closure objects
Helper items
 
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.

Expression-equivalent

Expression e is expression-equivalent to expression f, if

  • e and f have the same effects, and
  • either both are constant subexpressions or else neither is a constant subexpression, and
  • either both are potentially-throwing or else neither is potentially-throwing (i.e. noexcept(e) == noexcept(f)).

Notes

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

Example

Displays values for each type of quark in particle phyics.

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

Output:

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

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

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)
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)
BLAS-like slice of a valarray: starting index, length, stride
(class)