Long story short is it valid to:
map<int,int>m;
m.insert( make_pair( 1, 40 ) );
for( map<int,int>::iterator it = m.begin(); it != m.end(); ++it )
{
const_cast<int&>( it->first ) = 2;
}
it works, I have encountered myself in this problem, which in the real case the map was a map of two classes, map<classA,classB> and to access the non-const members of the class I had toconst_cast<classA&>(it->first).NonConstFunction(), this was the first idea that came up on my mind, is it just okay to do this or is there something better?
This is not allowed. When you modify the key in-place like this, the map will not “realize” that the value has changed, so it might need to move that node to a new position in the tree it maintains internally to store the data. If the tree is no longer sorted, almost any other operation on the tree may well crash and burn.
To do it correctly, you need to get a copy of the key/value pair, remove the old node from the map, modify your copy outside the map, then insert the modified copy back into the map.