2017-03-08 57 views
0

我已经编写了一个插入图形的小程序,它正在生成代码转储。我正在尝试遍历列表数据。 gdb调试器告诉我核心转储位置"cout<<it->first<<endl"这是奇怪,我的任何输入C++列表对遍历生成核心转储

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

需要[mcve]。仅仅因为一个程序在某一行发生了崩溃,这并不意味着这是该错误所在。显示的代码没有任何明显的错误,但是所显示的类违反了[三规则](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree),所以这可能是实际的错误;但没有[mcve]没有答案是可能的。 –

回答

1

在功能void Graph::printGraph(),在for循环中使用的是V这将是同样为所有的迭代。它应该是,

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

您已经声明string s,而不是在你的程序的任何地方使用它。

0

printGraph()V不应该用作循环中的索引(需要使用i)。 以下代码工程:

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