对的C ++动态向量

时间:2019-01-05 14:12:17

标签: c++ vector dynamic std-pair

我需要动态分配5个vectors中的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

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

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

1 个答案:

答案 0 :(得分:4)

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


声明:

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

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


如果要打印所有矢量 s ,则需要遍历数组的大小(已完成插入操作):

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;
    }
}
相关问题