Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::join — lazy range flattening

std::views::join creates a lazy view of elements from a range of ranges. It flattens one level, preserves order, and skips empty inner ranges without building a new container.

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

Syntax

#include <ranges>
std::views::join(r)
r | std::views::join

std::views::join, declared in <ranges>, is a range adaptor that creates a std::ranges::join_view. Writing r | std::views::join corresponds to calling std::views::join(r). The outer range and its inner ranges must support at least sequential reading as required by input_range.

The view flattens exactly one level: it visits the elements of successive inner ranges and skips empty ranges. It neither inserts separators nor creates a result container. In the example, the loop prints the spaces, not the adaptor.

For a container passed as an lvalue, the view refers to existing data. The container must remain alive while the view is used; avoid changes that invalidate iterators. When dereferencing yields a mutable reference, writing through that reference changes the source element.

Do not assume random access or an available size(), even when the source uses vectors. Iterator strength depends on the ranges and how their elements are exposed; join_view provides at most bidirectional iteration. The cited working draft is updated over time and is not a frozen C++23 specification.

Examples

#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<std::vector<int>> rows{{1, 2}, {}, {3, 4}};
    auto flat = rows | std::views::join;

    bool first = true;
    for (int value : flat) {
        if (!first) std::cout << ' ';
        std::cout << value;
        first = false;
    }
    std::cout << '\n';
}

Result

1 2 3 4

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