2013-02-15 32 views
5

矢量獲得價值爲什麼會在對的向量的迭代器訪問對的值時,下面的錯誤?錯誤從雙

vector< pair<int,string> > mapper; 
if(Hash(input, chordSize) != id){ 
    mapper.push_back(make_pair(tmp, input)); 
} 

for (vector< pair<int,string> >::iterator it = mapper.begin(); it != mapper.end(); ++it) 
{ 
    cout << "1st: " << *it.first << " "   // <-- error! 
     << "2nd: " << *it.second << endl;  // <-- error! 
} 

錯誤消息:

main_v10.cpp:165:25: error: ‘std::vector > >::iterator’ has no member named ‘first’ main_v10.cpp:165:56: error: ‘std::vector > >::iterator’ has no member named ‘second’

我該如何解決這個問題?

+1

您可能想要讀取運算符優先級,簽出'*'和'.'優先權: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B – billz 2013-02-15 07:58:52

回答

7

這是適用於三分球,太(迭代器的行爲很像指針)的問題。有訪問一個部件的值的指針(或迭代)指向兩種方式:

it->first  // preferred syntax: access member of the pointed-to object 

(*it).first // verbose syntax: dereference the pointer, access member on it 

的算符優先將您的表達成

*(it.first) // wrong! tries to access a member of the pointer (iterator) itself 

其嘗試訪問迭代器本身,它失敗的成員first,因爲它沒有一個成員叫first。如果確實如此,那麼您將取消該成員的價值。


但是,在大多數情況下,您應該使用std::map從鍵映射到值。取而代之的vector<pair<int,string> >,你應該使用map<int,string>其行爲類似於(插入,重複和東西也正好與對),但排序以更快的隨機訪問的數據結構中的鍵:

map<int,string> mapper; 
if(Hash(input, chordSize) != id){ 
    mapper.push_back(make_pair(tmp, input)); 
} 

for (map<int,string>::iterator it = mapper.begin(); it != mapper.end(); ++it) 
{ 
    cout << "1st: " << it->first << " " 
     << "2nd: " << it->second << endl; 
} 

注意之間的本質區別映射和對的向量是映射通過按鍵排列元素來重新排列元素。之後無法查詢插入的順序。有些情況下,你不想做的案件(當插入順序問題),所以在這種情況下,無論您的解決方案或至少含有鍵和值自定義類型的載體是正確的解決方案。

+0

我認爲第二個變體應該是'(*它).first' – 2013-02-15 07:43:36

+0

@ G-makulik當然,謝謝。 – leemes 2013-02-15 07:43:53

+0

是的,第二種選擇是正確的!謝謝。你真棒! – 2013-02-15 07:49:31