gpt4 book ai didi

c++ - 实现加权图的问题[c++]

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:10 25 4
gpt4 key购买 nike

我是编程新手,我尝试使用邻接表和 C++ 编程语言来实现图形。

图表数据的上传似乎有效。但是当我尝试打印图表时遇到了问题:Segmentation fault: 11。具体发生在57号顶点,我觉得程序逻辑没问题,就是不知道哪里出错了。

文本文件:data.txt

和源代码:

//
// main.cpp
// Dijkstra
//
// Created by Ibrahim El Mountasser on 02/12/2018.
// Copyright © 2018 Ibrahim El Mountasser. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

const int SIZE = 201;
struct Node{
int data;
int weight;
struct Node* next;

};
struct LinkedList {
struct Node* head;
};
class Graph {
public: LinkedList list[SIZE];
public:
Graph(std::string fileName) {
std::ifstream infile(fileName);
if(!infile.is_open()) return;
std::string line;

int i = 0;
while ( i < SIZE && getline(infile, line) )
{
std::istringstream str(line);
int u;
int w;

str >> u;
if ( u > SIZE )
{
// Problem.
std::cout<<"u is too large!"<<std::endl;
exit(-1);
}

int v;
char c;
while ( str >> v >> c >> w)
{
if( u < v)
{
createEdge(u, v, w);
std::cout<<"createEdge("<<u<<","<<v<<","<<w<<");"<<std::endl;
}
}

}


}
Node* createNode(int data, int weight){
Node* newNode = new Node;
newNode->data = data;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
void createEdge(int src, int dist, int weight) {
Node* newNode = createNode(dist, weight);
newNode->next = list[src].head;
list[src].head = newNode;
newNode = createNode(src, weight);
newNode->next = list[dist].head;
list[dist].head = newNode;

}
void printGraph() {
for (int i=0; i<SIZE; i++) {
std::cout<<i;

Node* temp = list[i].head;

while (temp != NULL) {
std::cout<<" -> "<<temp->data<<","<<temp->weight; // <== segfault here
temp = temp->next;

}
std::cout<<std::endl;
}
}
};
int main() {
Graph gr("data.txt");
gr.printGraph(); // <========= segfault when calling this

return 0;
}

最佳答案

我认为根本问题在于:

newNode->next = list[src].head;

list[src] 没有初始化,只是指向随机内存。当您执行 @rafix07 提到的操作并默认使用 nullptr 对其进行初始化时,它会起作用。

关于c++ - 实现加权图的问题[c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53580369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com