我有这个函数从这样格式化的文件中读取图形: numVerticies第一行的numEdges
每行每个边缘开始顶点结束顶点边缘颜色
所以它看起来像这样: 5 6
1 2 C
2 3 W
依旧......
C表示深红色,w表示白色。它适用于某些图形,但对于其他图形,我得到了一个seg错误。你能看看我的代码并告诉我它有什么问题吗? 这是一个工作正常的图表:https://i.stack.imgur.com/mPzx7.gif
我的代码:
//reading the graph the graph from the file and building an adj. matrix for it
int** read_graph(ifstream &fin, int &size) {
fin >> size; //reading the number of verticies
int edges;
fin >> edges; //num of edges
int** graph = new int*[size];
for (int i = 0; i < size; i++) { //creating the matrix
graph[i] = new int[size];
for (int j = 0; j < size; j++) {
if (i == j) graph[i][j] = 0; //0 if row and col match
else graph[i][j] = INT_MAX;
} //inf otherwise
}
for (int i = 0; i < edges; i++) { //reading the edges
int vert1, vert2;
char edge;
fin >> vert1 >> vert2 >> edge;
cout<<"ALIVE "<<vert1<<vert2<<endl;
//if Crimson - 1, else - MAX_EDGE
graph[vert1][vert2] = graph[vert2][vert1] = edge == 'C' ? 1 : MAX_EDGE;
cout<<"ALIVE END"<<endl;
}
return graph;
}
答案 0 :(得分:0)
我发现了这个错误。如果我的verticies的命名从0开始,则不会发生崩溃。如果它们从一个开始,则最后一个循环的最后一次运行会尝试访问未定义的区域。