c++ - 动态初始化和使用 C++ STL 列表数组

标签 c++ stl

我有一个类,其中我已将列表数组声明为数据成员。

list <int> **listOfNodes;

我在类的构造函数中为指向列表的指针分配了空间,如下所示(这里“v”是我想要的列表的编号,作为参数传递给构造函数。)

listOfNodes=new list<int>* [v];
for (int i = 0; i < v; ++i)
{
    list<int> temp;
    listOfNodes[i]=&temp;  //declaring a new list and making the list pointer point to it
}

现在我在函数中有以下代码,用于获取用户的输入并将其添加到相应的列表中。例如,如果用户输入 2 5,我需要将新条目 5 push_back 到索引为 2 的列表中,即 listOfNodes[2] 指向的列表。

int u,v;
cin>>u>>v;
(*(listOfNodes[u])).push_back(v);

但是,不知何故我的代码在执行时崩溃了。 有人可以指出我可能做错了什么吗。

最佳答案

for (int i = 0; i < v; ++i)
{
    list<int> temp;
    listOfNodes[i]=&temp;  
} // <- each temp is destructed here.

您的 temp 列表是自动分配的。这意味着一旦您离开循环范围,它们就会被破坏。现在您的 listOfNodes[i] 指向一些已破坏的内存(可能它们指向相同的位置,因为编译器每次都在相同的地址分配临时文件。尽管仍然无效。).

你应该这样做

for (int i = 0; i < v; ++i)
{
    listOfNodes[i] = new list<int>;  
}

并且不要忘记删除动态分配的内存。您可能应该只使用列表/列表 vector 或使用 smart pointers 的列表相反。

关于c++ - 动态初始化和使用 C++ STL 列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383544/

相关文章:

c++ - 使用单调时钟的绝对时间

c++ - 在linux中创建一个文件

c++ - ostream operator<< 为采用 STL 容器而重载,传递 std::string 会破坏它吗?

c++ - double > string > double 转换

c++ - 获取最接近 std::set 中给定元素的元素

c++ - 类和结构的高效 push_back

c++ - 使用迭代器调用STL Set中的非静态函数

c++ - 为什么遗留 C 标识符不需要 namespace 标准?

c++ - "Swapping values of two variables without using a third variable"中的潜在问题

c++ - C/C++如何将short转换为char