2017-03-08 53 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; 
    } 
}