我在使用 STL 的列表时遇到问题。 我正在加载格式为
的二合字母#of_tests
#of_vertexes #of_edges
#vertex1 > #vertex2
#vertex3 > #vertex4
...
但是我在第一次调用邻接列表上的 push_back 时得到了一个 SIGSEGV,我真的很困惑 - 列表数组已经初始化,所以我没有在 null 上调用它。
我已经检查了测试,并且我在范围内(我从来没有调用超出分配数组的方法)。
这是代码
#include <iostream>
#include <list>
using namespace std;
int * deg_in;
list<int> * edge;
int n;
int main()
{
int z;
cin >> z;
deg_in = new int[n]();
edge = new list<int>[n]();
while(z--)
{
int m;
cin >> n >> m;
while(m--)
{
int a, b;
char trash;
cin >> a >> trash >> b;
/// Vertexes are given 1 .. n, but stored 0 .. n - 1
a--;
b--;
edge[a].push_back(b); /// code fails here
deg_in[b]++;
}
/// do somethig with graph
delete [] deg_in;
delete [] edge;
}
return 0;
}
感谢任何帮助。
最佳答案
您的代码在输入 n
之前分配 deg_in
和 edge
数组。由于 n
是在全局范围内声明的,因此它被初始化为零,因此数组的长度为 0。因此出现 SIGSEGV,因为程序试图访问未分配的内存部分。
此外,您在尝试处理第一个测试用例后立即删除数组,并且不会为每个测试用例重新分配数组。
从上下文来看,deg_in
和 edge
数组似乎是针对每个测试用例的。在这种情况下,代码应该是:
while (z--)
{
int m;
cin >> n >> m;
deg_in = new int[n]();
edge = new list<int>[n]();
// input graph
delete [] deg_in;
delete [] edge;
}
正如 Paul R 所说,始终如一地格式化代码有助于减少犯简单错误的几率。干杯。
关于c++ - push_back 上的 STL 列表段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865682/