Home > Enterprise >  Unpacking Vector/Set in for loop
Unpacking Vector/Set in for loop

Time:12-23

Like in Python, we can unpack list of lists in a for loop as follows:

coordinates = [[2,2], [5,99]]
for x, y in coordinates:
    print(x y)

Is there any way to do the same with vector/set of vectors/sets in C ? Somewhat Like

vector<vector<int>> coordinates {{2,3}, {5,99}};
for(auto x, y : coordinates)
    cout << x y;

It's going to be nicer, if someone can provide solution in multiple c versions.

CodePudding user response:

Yes, but not with vector<vector<int>> because the size of (the inner) vector is not known at compile time. You need std::vector<std::pair<int, int>>:

std::vector<std::pair<int, int>> coordinates {{2,3}, {5,99}};
for(auto [x,y] : coordinates)
    cout << x y;

CodePudding user response:

I see that in your Q you have asked for unpacking a list of lists (as in Python). You can improve @bolov's answer by using an std::array (instead of a std::pair) inside your vector to have any number of elements in your inner container:

std::vector<std::array<int, 3>> coordinates{ {2,3,4}, {5,99,23} };
for (auto[x, y, z] : coordinates)
   std::cout << x   y   z;
    
std::cout << "Hello World!\n"; 
  • Related