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.
ranges::elements_view<R, 0>
.views::keys(e)
is expression-equivalent to keys_view<views::all_t<decltype((e))>>{e}
for any suitable subexpression e
.Expression e
is expression-equivalent to expression f
, if.
e
and f
have the same effects, and noexcept(e) == noexcept(f)
). keys_view
can be useful for extracting keys from associative containers, e.g. for (auto const& key : std::views::keys(map)) { /*...*/ }
.
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 │
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 |
(C++20) | takes a view consisting of pair-like values and produces a view of the second elements of each pair (class template) (range adaptor object) |
(C++20) | 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) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/ranges/keys_view