c++ - 在列表 vector 中的单个/多个列表中添加元素

标签 c++ list vector stl

我已经声明了一个列表 vector 和 3 个列表,并将这 3 个列表添加到 vector 中。现在,我想通过使用仅 vector 向这 3 个列表中的 2 个添加一些元素。我怎样才能做到这一点?
到目前为止,这是我的代码:

#include<iostream>
#include<list>
#include<vector>
using namespace std;


#ifndef ILIST
#define ILIST list<int>
#endif

#ifndef VLIST
#define VLIST vector<ILIST >
#endif

int main(int argc, char const *argv[])
{
    ILIST l1(4,10), l2(4,20), l3(4,30);
    VLIST vec;
    vec.push_back(l1);
    vec.push_back(l2);
    vec.push_back(l3);
    //here I want to add 2 elements in l2 and 1 in l3 by using the vector only. 
    return 0;
}

最佳答案

快速了解当前代码的作用:

ILIST l1(4,10), l2(4,20), l3(4,30);

三个局部变量。

VLIST vec;

局部 vector 。

vec.push_back(l1);

vector 现在分配一些动态内存来存储至少一个 ILIST,然后复制 l1 的内容到该内存中。两者现已独立。

如果你想要一个本质上是 View 的 vector ,允许你通过它来操作目标对象,你将需要在你的 vector 中存储一个指针或引用:

#include <iostream>
#include <list>
#include <vector>

using ilist_t = std::list<int>;
using vecilist_t = std::vector<ilist_t*>;

int main()
{
    ilist_t il;  // empty list
    vecilist_t vec;  // empty vector

    vec.push_back(&il);  // store address in vec[0]

    vec[0]->push_back(42);  // vec[0] has type `ilist_t*`, -> dereferences

    for (int i : il) {
        std::cout << i << '\n';
    }
}

正如您所指出的,您是一名学习者,我要指出的是,对于像这样的原始指针,您有责任确保指向的对象持续存在的时间长于它们通过 vector 的潜在用途:

vecilist_t f() {
    ilist_t i;
    vecilist_t v;
    v.push_back(&i);
    return v;
}

int main() {
    auto v = f();
    v[0]->push_back(42);  // undefined behavior, probably crash
}

f 返回的 vector 具有 i 的地址,它具有自动存储持续时间 - 它的生命周期结束于函数范围的末尾,使指向它的指针在我们返回的对象无效,随之而来的是未定义的行为。

--- 编辑 ---

不清楚为什么需要独立列表。如果你想要的只是一个包含 3 个列表的 vector ,你可以执行以下操作:

#include <vector>
#include <list>

using ilist_t = std::list<int>;
using ilvec_t = std::vector<ilist_t>;

int main() {
    ilvec_t ilvec;
    ilvec.resize(3);  // now contains 3 empty lists.

    // push a value onto the 2nd list
    ilvec[1].push_back(42);
}

如果您的 vector 将具有编译时固定大小,您可以改用 std::array。

using ilarray_t = std::array<ilist_t, 5>;  // compile time size fixed at 5.

关于c++ - 在列表 vector 中的单个/多个列表中添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426997/

相关文章:

c++ - 浮点比较

c++ - vector 类 : Difference between 4 floats, 或 4 个 float 的数组

c# 字母数字列表排序通过检查列表项是否包含

C++ 将 vector 中的 vector 组合成一个 vector

c++ - C++ 中的模板 vector

c++ - 我的解决方案有什么问题?

c++ - TFTP 源代码示例

html - 响应列表创建新列

python - 检查一个列表中是否至少有 2 个值在另一个列表中

c++ - 调用 std::vector::push_back() 会更改 vector 中先前的元素吗?