在 for 循环中解包 Vector/Set

Unpacking Vector/Set in for loop

与Python一样,我们可以在for循环中解压列表列表,如下所示:

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

有什么方法可以在 C++ 中对 vectors/sets 的 vector/set 做同样的事情吗? 有点像

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

如果有人能提供多个c++版本的解决方案就更好了。

是的,但 vector<vector<int>> 不是,因为(内部)向量的大小在编译时未知。你需要 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;

我看到在您的 Q 中您要求解包列表列表(如 Python 中)。您可以通过在向量中使用 std::array(而不是 std::pair)来改进@bolov 的答案,以便在内部容器中包含任意数量的元素:

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";