2013-10-29 70 views
2

名單我有這樣的代碼:遍歷向量C++

#include <iostream> 
#include <vector> 
#include <list> 

using namespace std; 

class Graph { 
    public: 
     //Create graph with n nodes 
     Graph(int size); 
      ~Graph(); 

     //Initialize graph 
     void InitializeGraphWithRandomNum(); 


    private: 

     vector <list <int*> > *graph; 

}; 


void Graph::InitializeGraphWithRandomNum() { 
    //Here I want to iterate 
    for (int i=0; i< graph->size(); i++) { 
     std::list <int*>::iterator it; 
     for (it = graph[i].begin(); it< graph[i].end();++it) { 
       .......... 
      } 

    } 
} 

什麼錯在這裏。它說

在'it =(((Graph *)this) - > Graph :: graph +((unsigned int)(((unsigned int)i)* 12u)中'operator ='不匹配。 ) - > std :: vector < _Tp,_Alloc> ::以_Tp = std :: list開始,_Alloc = std :: allocator>,std :: vector < _Tp,_Alloc> :: iterator = __gnu_cxx :: __ normal_iterator * ,性病::矢量>>,類型名稱的std :: _ Vector_base < _TP,_Alloc> :: _ Tp_alloc_type ::指針=標準::名單*」 DejkstraAlg.cpp

謝謝 最佳

回答

3

graph是指向矢量的指針,而不是矢量。將其聲明爲矢量,或使用(*graph)[i].begin()

1

是一個指向向量,也迭代比較end()使用operator!=代替operator<

for (it = (*graph)[i].begin(); it != (*graph)[i].end(); ++it) 
//        ^^^ 

更好的只是寫:

vector <list<int>> graph; 
0

錯誤poits到statemenet(你做不顯示)你試圖給列表的一個元素賦值的地方。我想你忘了*它有int類型的指針。 所以不是

*it = value; 

你必須寫

**it = value; 
3

更改爲

void Graph::InitializeGraphWithRandomNum() 
{ 
    typedef list<int*> int_list; 
    typedef vector<int_list> int_list_vector; 

    for (int_list_vector::iterator vectit = graph->begin(); vectit != graph->end(); ++vectit) 
    { 
     for (int_list::iterator listit = vectit->begin(); listit != vectit->end(); ++listit) 
     { 
      int* value = *listit; 
     } 
    } 
} 

或者乾淨多了,如果你有C++ 11(不包括在你的標籤,但可能對其他人有用):

void Graph::InitializeGraphWithRandomNum() 
{ 
    for (auto vectit = graph->begin(); vectit != graph->end(); ++vectit) 
    { 
     for (auto listit = vectit->begin(); listit != vectit->end(); ++listit) 
     { 
      int* value = *listit; 
     } 
    } 
} 

如果你是到C++ 11個非成員開始/結束,許多C++ - ERS(像我)是支持者:

void Graph::InitializeGraphWithRandomNum() 
{ 
    for (auto vectit = begin(*graph); vectit != end(*graph); ++vectit) 
    { 
     for (auto listit = begin(*vectit); listit != end(*vectit); ++listit) 
     { 
      int* value = *listit; 
     } 
    } 
} 
+0

使用'auto'的迭代器也將工作,和可能會更整潔。 –

+1

他沒有在他的標籤中提到C++ 11,所以我省略了這一點。將添加ALT版本:) –

+0

基於範圍的循環將使C++ 11部分更漂亮。 – YoungJohn