我的 c++ 代码不适用于图形

My c++ Code is not working for a Graph

本文关键字:适用于 图形 不适用 代码 c++ 我的      更新时间:2023-10-16

我正在用c ++为图形编写代码,但存在一些问题。它无法正常工作。请帮我它有什么问题?它的图形代码可以从用户那里获取图形的输入,并且图形中的每个边缘都具有特定的权重。 这是代码:

#include <iostream>
#include <vector>
using namespace std;
struct edge {
char src;
char dest;
int weight;
};
class Graph {
public:
vector<edge> edges;
int size,j=0;
//Constructor
Graph(int c) {
size=c;
}
void graphDesign(char s,char d,int w) {
edges[j].src=s;
edges[j].dest=d;
edges[j].weight=w;
j++;
}
void printGraph() {
for(int i=0; i<size; i++) {
cout<<edges[i].src<<"->"<<edges[i].dest<<"  :  
<<edges[i].weight<<endl;
}
}
};

int main() {
int e,i,w;
char s,d;
cout<<"Enter number of edges of graphs: ";
cin>>e;
Graph graph(e);
for(i=0; i<e; i++) {
cout<<"Enter source: ";
cin>>s;
cout<<"Enter destination: ";
cin>>d;
cout<<"Enter weight of the edge: ";
cin>>w;
graph.graphDesign(s,d,w);
}
graph.printGraph();
return 0;
}

这里有一个问题:

void graphDesign(char s,char d,int w) {
edges[j].src=s;
edges[j].dest=d;
edges[j].weight=w;
j++;
}

由于edges是一个空向量,因此访问edges[j]是非法访问。

在使用edges矢量之前,您需要适当调整其大小。

class Graph {
public:
vector<edge> edges;
//Constructor
Graph(int c) : edges(c) {}

这将创建一个包含c条目的向量。

此外,不要使用无关的、不必要的成员变量,例如此处的sizevector类具有一个size()成员函数,用于告诉您容器中有多少项。

使用像size这样的无关变量存在发生错误的风险,因为每当向量更改大小时都必须更新此变量。 与其尝试自己做这个家政服务,不如使用std::vector提供给您的size()功能。