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

标签 c++ 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 是空 vector ,访问 edges[j] 是非法访问。

在使用之前,您需要适本地调整 edges vector 的大小。

class Graph {
public:
     vector<edge> edges;

     //Constructor
     Graph(int c) : edges(c) {}

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

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

使用诸如 size 之类的无关变量会产生错误的风险,因为必须在 vector 更改大小时更新此变量。与其尝试自己做这些整理工作,不如使用 std::vector 提供给您的 size() 函数。

关于c++ - 我的 C++ 代码不适用于图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011443/

相关文章:

c++ - 很喜欢选择排序,现在不会排序

c++ - 模板参数是模板的模板类特化

c++ - 在 C++ 代码中接收段错误

c++ - -Wlifetime 标志的目的是什么?

java - gremlin是否需要将所有数据存储在java中?

python - 如何在 Django 网页中嵌入 matplotlib 图形?

c++ - 在 Qt 中,如何将 QString 注册到我的系统剪贴板,包括引用和非引用?

c# - ZedGraph 垂直线与 LineObj 问题

java - 如何在有向图上实现深度优先搜索访问所有顶点

android - 在 android 中绘制大型数据集的标准做法