3

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?

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

1 Answers1

3

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

康桓瑋
  • 33,481
  • 5
  • 40
  • 90