我的 c++ 代码不适用于图形
My c++ Code is not working for a Graph
我正在用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
条目的向量。
此外,不要使用无关的、不必要的成员变量,例如此处的size
。vector
类具有一个size()
成员函数,用于告诉您容器中有多少项。
使用像size
这样的无关变量存在发生错误的风险,因为每当向量更改大小时都必须更新此变量。 与其尝试自己做这个家政服务,不如使用std::vector
提供给您的size()
功能。
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- QT 样式表主题,适用于使用属性选择器的整个应用程序
- C++带有适用于左值和右值的引用参数的函数
- 代码适用于调试,但不适用于发布
- C++17 和更新的 std::分配器是否适用于动态数量的自定义堆?
- 适用于大型数组的无复制线程安全环形缓冲区
- NRVO 是否也适用于协程?
- 约束包容是否仅适用于概念?
- 程序只适用于包含(无副作用)cout声明
- 适用于频繁更改的大型数据集的最佳数据结构
- 相同的 for 循环适用于其他项目,但不适用于此项目。为什么?
- 无法让 FastNoise 适用于草地
- 其中列 = 值,仅适用于整数值