我正在研究一个实现Dijkstra算法的程序。创建指针向量时的分段错误(C++)
我第一次在txt文件数据读入指针数组的向量,所以我可以使用它。 (该文件包含顶点数(在这种情况下为7),顶点及其各自的边和重量)。请看下图:
7
2
2 2
4 1
2
4 3
5 10
2
1 4
6 5
4
3 2
5 2
6 8
7 4
1
7 6
0
1
6 1
在我Main.cpp的我试图创建的指针下面的行向量到顶点对象:
vector<Vertex*> vertices;
然后我试图填充矢量与下面的代码:
for(int i=1;i < numVertices; i++)
{
file >> numEdges;
cout << "At vertex " << i << " the number of edges is " << numEdges << endl;
vertices[i] = new Vertex();
//Vertex newVertex;
//Using the i counter variable in the outer for loop to identify
//the what vertex what are currently looking at in order to read in the correct adjacent vertex and weight
cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
vertices[i]->setVertexNum(i);
//newVertex.setVertexNum(i);
for(int j=1;j<=numEdges;j++)
{
file >> adjacentVertex;
cout << "The adjacent vertex is: " << adjacentVertex << endl;
file >> weight;
cout << "The weight is: " << weight << endl;
cout << endl;
vertices[i]->setAdjacentVertex(adjacentVertex, weight);
}
//cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
vertices.push_back(vertices[i]);
}
但是,我得到一个seg故障,我不明白为什么。我之前宣布了像这样的指针向量,没有任何问题,我希望这里有人能够指出我正确的方向。
虽然因为如果我改变矢量初始化下面,我没有得到一个赛格故障有趣的是:
vector<Vertex*> vertices(numVertices + 1, NULL);
不过,我不想矢量预置为特定的大小,我只是想要它初始化。
谢谢
你为什么从1开始你的循环? C++中的数组索引从0开始。 – PaulMcKenzie
这就是为什么我们有调试器。当然,有人可以为你发布一个答案,但是这对你如何解决自己的问题有帮助吗?你有没有尝试过调试器? –
在哪一行代码中发生段错误? –