为什么我的代码会抛出异常?
代码定义了一个名为 Graph 的类,它表示一个图。图是由节点和边组成的数据结构。节点代表图的顶点,边代表节点之间的连接。
Graph 类具有以下成员:
数组:节点数组。 大小:图表的大小。 j:用于跟踪数组中下一个可用索引的计数器。 Graph 类提供了以下方法:
addvertex():向图中添加一个顶点。 add_edge_no_direction():在图中的两个顶点之间添加无向边。 display():显示图形。 main() 函数创建一个大小为 200 的新 Graph 对象。然后它向图中添加五个顶点以及顶点之间的四个无向边。最后调用display()方法来显示图表
c
#include <iostream>
using namespace std;
struct node {
int data;
int weight;
node* next;
node() {}
node(int data, int weight) {
this->data = data;
next = nullptr;
this->weight = weight;
}
};
class Graph {
private:
node* array;
int size;
int j;
public:
Graph(int size) {
this->size = size;
array = new node[size];
j = 0;
for (int i = 0; i < size; i++) {
array[i].data = 0;
array[i].weight = 0;
array[i].next = nullptr;
}
}
bool addvertex(int value) {
for (int i = 0; i < size; i++) {
node* current = array[i].next;
while (current != nullptr) {
if (current->data == value) {
return false;
} else {
current = current->next;
}
}
}
node* newnode = new node(value, 0);
newnode->next = nullptr;
array[j].next = newnode;
j++;
return true;
}
bool add_edge_no_direction(int source, int destination, int weight) {
node* newnode1 = new node(source, weight);
node* newnode2 = new node(destination, weight);
// check if edge present
for (int i = 0; i < size; i++) {
if (array[i].data != source || array[i].data != destination) {
return false;
}
}
for (int i = 0; i < size; i++) {
node* current = array[i].next;
if (current->data == source || current->data == destination) {
if (current->next == nullptr) {
if (current->data == source) {
current->next = newnode2;
} else {
current->next = newnode1;
}
} else {
while (current->next != nullptr) {
current = current->next;
}
if (current->data == source) {
current->next = newnode2;
} else {
current->next = newnode1;
}
}
} else {
cout << "no way it comes here";
}
}
return true;
}
void display(){
for(int i=0;i<size;i++){
node* current=array[i].next;
cout<<current->data;
while(current){
cout<<"->";
current=current->next;
cout<<current->data;
}
}
}
};
int main() {
Graph g1(200);
g1.addvertex(1);
g1.addvertex(2);
g1.addvertex(3);
g1.addvertex(4);
g1.addvertex(5);
g1.add_edge_no_direction(1, 2, 100);
g1.add_edge_no_direction(1, 3, 150);
g1.add_edge_no_direction(1, 4, 200);
g1.add_edge_no_direction(1, 5, 250);
g1.display();
}
如果您在调试器下运行代码,您将看到发生异常,因为您没有在显示方法中检查空指针。
当遇到异常时,您应该始终使用调试器。
固定代码为:
void display()
{
for (int i = 0; i < size; i++)
{
node *current = array[i].next;
if (!current)
continue;
cout << current->data;
while (current)
{
cout << "->";
current = current->next;
if (!current)
break;
cout << current->data;
}
}
}