我正在用 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
是空 vector ,访问 edges[j]
是非法访问。
在使用之前,您需要适本地调整 edges
vector 的大小。
class Graph {
public:
vector<edge> edges;
//Constructor
Graph(int c) : edges(c) {}
这将创建一个包含 c
条目的 vector 。
此外,不要不在此处使用无关的、不必要的成员变量,例如size
。 vector
类有一个 size()
成员函数来告诉您容器中有多少项。
使用诸如 size
之类的无关变量会产生错误的风险,因为必须在 vector 更改大小时更新此变量。与其尝试自己做这些整理工作,不如使用 std::vector
提供给您的 size()
函数。
关于c++ - 我的 C++ 代码不适用于图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011443/