Reputation: 722
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.
Upvotes: 1
Views: 2026
Reputation: 8427
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";
Upvotes: 3
Reputation: 75688
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;
Upvotes: 5