Skip links

What is std::views::zip in C++?

std::views::zip was introduced in the <ranges> library as part of C++23. This is quite convenient when we want to iterate over two or more ranges in lockstep, taking one element from each at every step. It is a superior alternative to the conventional index loop.

The following example shows the typical usage:

std::views::zip
std::views::zip

The code above uses two vectors of different types, and the for loop uses zip to iterate over the different pairs. Zip takes any number of ranges (including zero) and returns std::views::zip_view. Each element of that view is a std::tuple containing elements at the corresponding position in each input range.

Here is the output – no surprises:

The output
The output

One nice thing to note is that the input elements passed need not all have the same size. Zip handles this correctly by stopping when any input ends. Naturally, an empty input makes the result empty.

The number of inputs determines the number of tuple components. The zero argument call returns an empty view of std::tuple<>.

Look at this example:

Different input sizes
Different input sizes

Here each collection has a different size – minimum of 3 and maximum of 5. The result will therefore have only 3 tuples (with 3 elements each). Check the output:

Program output
Program output

It is important to keep in mind that the zip_view tuples hold references to the original elements. This can cause surprise if we inadvertently mutate them. This is shown in the following example:

Holding references
Holding references

Line 39, which checks if the values are indeed references, returns true to confirm this. Here is the output:

The output
The output

C++23 also introduced std::views::zip_transform. It passes the corresponding elements from std::views::zip as separate arguments to a callable and yields the callable’s result. Take a look at this:

The zip_transform function
The zip_transform function

The corresponding output is:

Program output
Program output

std::views::zip provides the same functionality as the zip() function does in Python. As the above examples illustrate, it is quite useful when working with multiple collections.

You can download the source here.

Have a nice weekend!

Leave a comment