2010-10-27 65 views
1

我有一個STL映射,我想要遍歷,並且似乎無法讓代碼工作。該代碼是:STL映射迭代器複製的問題

//PowerupInfo is a struct defined in this class's header file 
std::map<std::string, PowerupInfo> powerups; 

...populate powerups 

std::map<std::string, PowerupInfo>::iterator iter; 
for (iter = powerups.begin(); iter != powerups.end(); iter++) { 
    return iter->second.type ; 
} 

該錯誤消息我得到的是:

error: no match for 'operator=' in 'iter = (((const std::map<std::string, PowerupInfo, std::less<std::string>, std::allocator<std::pair<const std::string, PowerupInfo> > >)((const PowerupList)this)) + 24u)->std::map<_Key, _Tp, _Compare, _Alloc>::begin with _Key = std::string, _Tp = PowerupInfo, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, PowerupInfo> >'| note: candidates are: std::_Rb_tree_iterator<std::pair<const std::string, PowerupInfo> >& std::_Rb_tree_iterator<std::pair<const std::string, PowerupInfo> >::operator=(const std::_Rb_tree_iterator<std::pair<const std::string, PowerupInfo> >&)|

所以我通常會認爲這個問題已經做設置ITER等於東西它不喜歡,因爲它是找不到'operator ='的匹配項。但爲什麼?爲什麼這項任務不能工作?

編輯:

原來的方法進行常量,從而使參考通電爲常量,以及,導致錯誤。我只是在閱讀我自己的代碼時做得不好。多謝你們!

+0

你確定'iter = powerups.begin()'而不是'iter = poweruplist.begin()'是你的實際意圖嗎? – Keynslug 2010-10-27 05:38:12

回答

3

您的地圖名稱是poweruplist而不是powerups(您在for循環中使用此名稱)。如果這不是錯誤的原因,那麼它看起來像你是for循環是在一個函數接受由const引用地圖(或是一個類的常量成員函數)。在這種情況下,您的迭代器類型應該是const_iterator而不是iterator

+0

哎呦,我的錯字。修正了,謝謝! – Lewis 2010-10-27 05:35:32

+1

你的意思是你現在沒有收到編譯器錯誤,或者是在發佈這個問題時發生了錯字? – Naveen 2010-10-27 05:36:42

+0

發佈問題時發生錯字。 powerups是類Poweruplist的成員,我感到困惑:D – Lewis 2010-10-27 05:43:49

1

重新格式化錯誤代碼,使其可讀:

error: no match for 'operator=' in 
    'iter = 
    ((
     (const std::map<std::string, PowerupInfo>*)((const PowerupList*)this) 
    ) 
     + 24u 
    )->std::map<std::string, PowerupInfo>::begin()' 

看起來不錯誤信息給你提供的代碼。
請剪下並翻過代碼。否則它是沒有意義的。