Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/ranges/values view"

From cppreference.com
< cpp‎ | ranges
(add vector .second example)
(fix output)
Line 53: Line 53:
 
|output=
 
|output=
 
Odd values in the map: 1 3 5
 
Odd values in the map: 1 3 5
 +
.second values in the vector: 10 20 30
 
}}
 
}}
  

Revision as of 07:35, 10 June 2022

 
 
Ranges library
Range adaptors
 
Defined in header <ranges>
template<class R>
using values_view = ranges::elements_view<R, 1>;
(1) (since C++20)
namespace views {

    inline constexpr auto values = ranges::elements<1>;

}
(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 second element of the adapted view's value-type.

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

Contents

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

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

Example

#include <iostream>
#include <ranges>
#include <vector>
#include <map>
 
int main()
{
    std::map<char, int> map{ {'A', 1}, {'B', 2}, {'C', 3}, {'D', 4}, {'E', 5} };
 
    auto odd = [](int x) { return 0 != (x & 1); };
 
    std::cout << "Odd values in the map: ";
    for (int value : map | std::views::values | std::views::filter(odd))
        std::cout << value << ' ';
 
    std::vector<std::pair<int, int>> vec{ {1, 10} , {2,20}, {3, 30} };
    std::cout << std::endl;
    std::cout << ".second values in the vector: ";
    for (int value : vec | std::views::values)
        std::cout << value << ' ';
 
}

Output:

Odd values in the map: 1 3 5
.second values in the vector: 10 20 30

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 first 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 Nth element of each tuple
(class template) (range adaptor object)[edit]
BLAS-like slice of a valarray: starting index, length, stride
(class) [edit]