C++ 动态向量对

C++ dynamic vector of pairs

我需要动态分配 5 vectors of pairs 的数组。此代码片段应该将第一个元素添加到所有 5 vectors:

std::vector<std::pair<int, int>> * arr = new std::vector<std::pair<int, int>>[5];
for (int i = 0; i < 5; i++) {
    arr[i].push_back(std::make_pair(i+1, i+11));
}

但它只向 arr[0] 向量添加 1 个元素

for (auto el : *arr) {
    std::cout << el.first << ", " << el.second << std::endl;
}

打印出 1, 11
我需要的是

1, 11
2, 12
3, 13
4, 14
5, 15

请给我一些提示。如何使用成对的动态向量?

编辑: 向量的向量是一种可能的方式。但是,我想使用向量数组。

注意: 由于编辑了问题而编辑了整个答案。


声明:

for (auto el : *arr) {
    std::cout << el.first << ", " << el.second << std::endl;
}

将仅打印第一个向量的元素(即 arr[0])。 那是因为 arr 会衰减为指向数组第一个元素的指针。


如果你想打印所有向量s,你需要迭代array的大小(正如已经为插入):

for (int i = 0; i < 5; i++) {
    // arr[i] now is the i-th vector, and you can print whatever you want

    // For example the following will print all element for each vector.
    for (auto el : arr[i]) {
      std::cout << el.first << ", " << el.second << std::endl;
    }
}