0

I have written small program for insert edge into graph and it is generating code dump. I am trying to traverse list data. gdb debugger show me core dump location "cout<<it->first<<endl" which is strange for me Any input

#include<iostream>
 #include<utility>
 #include<vector>
 #include<string>
 #include<list>

 using namespace std;

 class Graph {
     private:
         int V;
         list<pair <int,int> > *adj;
     public:
         Graph(int V);
         void addedge(int V, int U, int w);
         void printGraph();
 };

 Graph::Graph(int V)
 {
     this->V = V;
     adj = new list<pair <int, int> >[V];
 }

 void Graph::addedge(int V, int U, int W) {
     adj[V].push_back(make_pair(U,V));
 }

 void Graph::printGraph() {
     for(int i=0; i<V; i++){
         string s = to_string(V) + "->";
         for(list<pair<int,int> >::iterator it = adj[V].begin(); it != adj[V].end(); ++it) {
             cout<<it->first<<endl;
         }
     }
 }
 int main() {
     Graph g(10);
     g.addedge(0, 1, 2);
     g.addedge(1, 1, 2);
     g.addedge(2, 1, 2);
     g.printGraph();
     return 0;
 }
abhi1984
  • 11
  • 3
  • A [mcve] is required. Just because a program crashed on one particular line, that doesn't mean that's where the bug is. There's nothing explicitly wrong with the shown code, but the shown class violates [the Rule Of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three), so that could be the actual bug; but without a [mcve] no answer is possible. – Sam Varshavchik Mar 08 '17 at 04:27

2 Answers2

1

In function void Graph::printGraph(), inside for loop you are using V which will be same for all the iterations. It should be,

for(list<pair<int,int> >::iterator it = adj[i].begin(); it != adj[i].end(); ++it)

You have declared string s and not using it anywhere in your program.

Akshay Patole
  • 454
  • 3
  • 14
0

In printGraph(): V should not be used as index in the loop (need to use i). Below code works:

 void Graph::printGraph() {
   for(int i=0; i<V; i++){
     string s = to_string(i) + "->";
     for(list<pair<int,int> >::iterator it = adj[i].begin(); it != adj[i].end(); ++it)
         cout<< s << it->first<< " and weight is [" << it->second <<"]"<< endl;
    }
 }
Arash
  • 1,950
  • 14
  • 17