Combine Multiple Ranges Element-wise with views::zip in C++23

Combine Multiple Ranges Element-wise with views::zip in C++23

Working with several sequences at the same time is a frequent requirement, especially when related data is stored in separate containers. Traditional approaches often involve indexing or iterators, which can introduce extra complexity and reduce clarity.

Since C++23, the standard std::ranges library provides the std::views::zip adaptor, which allows multiple ranges to be traversed in parallel. It produces a new view where each element is a tuple containing corresponding items from the input ranges.

The following example shows how views::zip can be used to pair elements from two containers:

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

int main() {
    std::vector a = {1, 2, 3};
    std::vector b = {'a', 'b', 'c'};

    for (auto [num, ch]: std::views::zip(a, b)) {
        std::cout << num << " -> " << ch << std::endl;
    }

    return 0;
}

Output:

1 -> a
2 -> b
3 -> c

In this example, the views::zip combines the two vectors into a single range of pairs. Each iteration yields elements taken from the same position in both containers, making it straightforward to process them together.

It is worth noting that the resulting range stops when the shortest input range is exhausted. This behavior ensures safe iteration without accessing elements beyond the bounds of any container. Additionally, the adaptor is not restricted to two inputs - it can operate on three or more ranges.

Leave a Comment

Cancel reply

Your email address will not be published.