简体   繁体   中英

My c++ Code is not working for a Graph

I am writing a code for a graph in c++ but there is some problem. It is not working properly. Please help me what is the problem with it? Its code for a graph which can take inputs for graph from user and each edge in graph has specific weight. Here is the code:

#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;
}

One issue is here:

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

Since edges is an empty vector, accessing edges[j] is an illegal access.

You need to size the edges vector appropriately before you use it.

class Graph {
public:
     vector<edge> edges;

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

This creates a vector with c entries.

Also, do not use extraneous, unnecessary member variables such as size here. The vector class has a size() member function to tell you how many items are in the container.

Using extraneous variables like size runs the risk of bugs occurring due to having to update this variable anytime the vector changes size. Instead of trying to do this housekeeping yourself, use the size() function provided to you by std::vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM