我想实现一个使用邻接表的图形数据结构。为了填充,我必须从文件读取数据。该文件是一个文本文件,第一行包含两个数字。第一个是顶点数n,第二个是边数m。在这条线后面会有三行数字的m行。前两个数字表示无向边缘的源和目标顶点。第三个数字(正整数)是该边缘的权重。C++程序崩溃。图形执行
该文件的内容是这样的:
5 7
0 1 3
0 2 4
0 3 5
1 4 10
2 5 20
3 4 6
4 5 4
但由于某些原因,我至今写的代码,使程序崩溃。编译器没有提供任何关于原因的提示。 我真的很感谢一些建议。我已经读了很多关于C++中的指针和引用,但仍然发现它们令人困惑。所以更好地理解它们的好资源真的会有所帮助。
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct Vertex
{
unsigned value;
vector<Vertex*> adjList;
vector<unsigned> weights;
};
class Graph
{
private:
unsigned vertex_count, edge_count;
vector<Vertex*> vertices;
public:
Graph(string fileName)
{
ifstream myFile(fileName);
if (myFile.is_open())
{
// Processing the first line of the file
string aLine;
getline(myFile, aLine);
stringstream aString(aLine);
aString >> vertex_count;
aString >> edge_count;
// Processing the rest of the file
unsigned vert1, vert2, weight;
while (getline(myFile, aLine))
{
aString= stringstream(aLine);
aString >> vert1;
aString >> vert2;
aString >> weight;
addRelation(vert1, vert2, weight);
}
}
else
cout << "Unable to open file.";
}
~Graph()
{
for (unsigned i = 0; i < vertices.size(); i++)
delete vertices[i];
}
void addVertex(unsigned val)
{
Vertex* newVertex = new Vertex;
newVertex->value = val;
vertices.push_back(newVertex);
}
Vertex* findVertex(unsigned val)
{
for (unsigned i = 0; i < vertices.size(); i++)
if (vertices[i]->value = val)
return vertices[i];
return nullptr;
}
void addRelation(unsigned vert1, unsigned vert2, unsigned weight)
{
Vertex* vertex1 = findVertex(vert1);
if (vertex1 == nullptr) {
addVertex(vert1);
vertex1 = findVertex(vert1);
}
Vertex* vertex2 = findVertex(vert2);
if (vertex2 == nullptr) {
addVertex(vert2);
vertex2 = findVertex(vert2);
}
vertex1->adjList.push_back(vertex2);
vertex1->weights.push_back(weight);
vertex2->adjList.push_back(vertex1);
vertex2->weights.push_back(weight);
}
};
int main()
{
Graph myG("graph.txt");
return 0;
}
首先,使更多的警告,它总是好的发展时,更高的警告级别。其次,在调试器中运行以查找崩溃。调试器将停在崩溃的位置,让你检查(并向上)函数调用堆栈,并让你检查每个级别的变量值。当然,您需要使用debug-info构建它才能工作。 –