Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::values — a view of second elements

std::views::values creates a lazy view of index-1 elements from pairs or tuples. It lets you traverse map values or modify the second fields of pairs without creating a separate container.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <ranges>
std::views::values(range)
range | std::views::values

std::views::values, available through <ranges>, is a range adaptor equivalent to std::views::elements<1>. It selects the second element of each supported tuple-like value, such as std::pair or std::tuple. It is not limited to maps; the range must satisfy the adaptor's requirements.

The expression range | std::views::values corresponds to calling std::views::values(range). The result is a lazy view, not a new container of extracted values. std::ranges::values_view<R> is a type alias for std::ranges::elements_view<R, 1>, whereas std::views::values is the adaptor object.

If the range exposes references to mutable pairs, the view exposes references to their second fields. Whether assignment is possible depends on what the view yields. For a pair exposed as const std::pair<int, int>&, the view yields const int&, which does not allow writing through it. For const std::pair<int, int&>&, the view still yields int&, so assignment through the view can modify the referenced integer. If the range returns elements by value, the view may yield values rather than references. A view created from an lvalue container does not extend its lifetime: the container must remain alive while the view is used.

In the example, int& allows modification of the original second fields, so the expected output is 11 21 31. Using int instead of int& would modify only local copies. The displayed code was run unchanged in an isolated environment, and its standard output matched the expected output exactly.

Examples

#include <array>
#include <iostream>
#include <ranges>
#include <utility>

int main() {
    std::array<std::pair<int, int>, 3> entries{{{1, 10}, {2, 20}, {3, 30}}};
    auto values = entries | std::views::values;

    for (int& value : values) {
        value += 1;
    }

    std::cout << entries[0].second << ' '
              << entries[1].second << ' '
              << entries[2].second << '\n';
}

Result

11 21 31

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources