CKTIS / C++
std::views::zip — iterate over ranges together
std::views::zip creates a lazy view of elements at corresponding positions in several ranges. Iteration stops at the shortest range, and reference access lets you modify mutable source elements.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <ranges>
std::views::zip(r1, r2, ...)std::views::zip, available in C++23 in <ranges>, combines corresponding positions of ranges into a lazy view. It does not build a result container. For a nonempty argument list it creates a std::ranges::zip_view, adapting inputs through std::views::all. Inputs must support that adaptation and at least input iteration.
Iteration stops when any range reaches its end: excess elements are skipped, with no padding or length-mismatch report. If all inputs provide a size, size() returns their minimum size. Calling std::views::zip() without arguments produces an empty view whose element type is std::tuple<>.
Dereferencing yields a tuple of input-iterator dereference results—usually references, but sometimes proxy objects. Using auto&& [number, letter] lets you work with these elements without copying their values. Changing number in the example changes numbers. If std::views::all adapts an lvalue by reference, the referenced range must remain alive while the zip view uses it. If the argument is a view that can be copied from the supplied lvalue, std::views::all instead copies the view itself, not necessarily its elements. For example, the original std::ranges::single_view<int> can be destroyed while the zip view continues to use its own copy. Any underlying storage that the copied view still uses must remain valid, and iterator-invalidation rules still apply.
The example processes only two pairs, so the third element of numbers remains 3. A standard library implementing this C++23 feature is required; the compiler flag alone does not establish availability or attest operation in a production runtime.
Examples
#include <array>
#include <iostream>
#include <ranges>
#include <tuple>
int main() {
std::array<int, 3> numbers{1, 2, 3};
std::array<char, 2> letters{'a', 'b'};
for (auto&& [number, letter] : std::views::zip(numbers, letters)) {
number *= 10;
std::cout << number << ':' << letter << '\n';
}
std::cout << numbers[2] << '\n';
}
Result
10:a 20:b 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.