2014-01-21 3 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을 변경할 수 있지만 은 읽기 전용입니다 (const).

관련 문제