2017-10-09 41 views
27

這裏是我的代碼:遞減STD月底::地圖

#include <iostream> 
#include <map> 
using namespace std; 

int main() { 
    map<int , int > myMap; 

    map<int , int>::iterator it; 

    myMap.insert(pair<int , int>(1,2)); 
    myMap.insert(pair<int , int>(671,223)); 
    myMap.insert(pair<int , int>(353,245352)); 

    it = myMap.end() - 1; 

    cout << it->first << it->second << endl; 

    return 0; 
} 

編譯此代碼會產生以下編譯錯誤:

error: no match for ‘operator-’ (operand types are ‘std::map<int, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const int, int> >}’ and ‘int’) 
    it = myMap.end() - 1; 

我不知道爲什麼我收到此錯誤因爲我認爲算術運算在所有類型的迭代器中都是允許的。

回答

41

並非所有的迭代器類別都支持算術運算,這是一種誤解。如果你的目標寫更通用的代碼,你可以使用std::prev

it = std::prev(myMap.end()); 

它需要一個雙向迭代器,這std::map的迭代器。如果您想要將迭代器移動多個步驟,它還可以接受指定移動迭代器的距離的第二個參數。

另外,當你傳遞一個隨機訪問迭代器時,它將和算術一樣快。

+0

錯誤:'prev'不是'std'的成員,我收到此錯誤。我需要一些頭文件嗎? –

+1

@BhawandeepSingla - '' – StoryTeller

+0

我收錄了它,仍然收到相同的錯誤。還有什麼其他的東西需要補充? –