2014-01-21 76 views
1

在下面的例子中,我嘗試插入一個元素到std::map並獲取到最後一個插入元素的迭代器,但我無法修改它。修改最後一個插入到std :: map

#include <map> 

struct X { 
    int x; 
}; 

struct Y { 
    int y; 
}; 

int main() 
{ 
    X x = {1}; 
    Y y = {2}; 

    std::map <X, Y> Z; 
    std::pair<std::map<X, Y>::iterator,bool> lastval = Z.insert(std::pair<X, Y>(x, y)); 

    // Error: Expression must be a modifiable lvalue; 
    lastval.first->first.x = 0; 
} 

我該怎麼做?

回答

3

std::map(和std::set的元素)中的鍵是不可變的 - 您無法更改它們,因爲這可能會改變排序並破壞地圖。 std:map<K, V>類型的值實際上是std::pair<const K, V>。所以在你的情況下,lastval.first->second可以改變,但lastval.first->first是隻讀的,因爲它是const