[SOLVED] How do I joint iterate over 2 vectors by ref?

Issue

This Content is from Stack Overflow. Question asked by Arsen Zahray

I’m trying to iterate over 2 vectors in one go using std::views::join

Here is what I’m trying:

std::vector<int> a {1, 2, 3}, b {4, 5, 6};
    for (auto &v : {a, b} | std::views::join)
    {
        std::cout << v << std::endl;
    }

This fails to compile. Now, if I change the code to:

for (auto &v : std::ranges::join_view(std::vector<std::vector<int>> {a, b}))
    {
        std::cout << v << std::endl;
        v++;
    }

it compiles and executes, however, the content of a and b is not modified.

How do I jointly iterate over a and b in a way where I can modify elements of a and b inside the loop?



Solution

How do I jointly iterate over a and b in a way where I can modify
elements of a and b inside the loop?

You can use views::all to get references to two vectors and combine them into a new nested vector

std::vector<int> a {1, 2, 3}, b {4, 5, 6};
for (auto &v : std::vector{std::views::all(a), std::views::all(b)} // <-
             | std::views::join)
{
  std::cout << v << std::endl;
  v++;
}

Demo


This Question was asked in StackOverflow by Arsen Zahray and Answered by 康桓瑋 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?