Home > Back-end >  How do I joint iterate over 2 vectors by ref?
How do I joint iterate over 2 vectors by ref?

Time:09-19

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?

CodePudding user response:

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

  • Related