How to modify the vlaue of a key-value Pair from a map while I do not know whether the key is exist in the map?
for example , there is a key-value pair in a map:
a[5] = " H ";
// But after some operation,like insert, erase etc ; I do not know whether 5 still exist in the map,can I modify it like this ?:
a[5] = " G ";
// or I must define a iteraotr pos
pos = my_map.find(5);
if( pos != my_map.end())
{
pos->second = " G ";
}
Is there any other way I can modify a value of a key-value Pair from a map??? Thanks!!!
The standard map has the curious property that indexing into an element that is not present in the map causes an association to be created between that key and a default constructed value. So, if the element
5is not present as a key in the map, after you doa[5]it will exist and be associated to an empty string.C++11 added a new
atmethod that throws if the key does not exist in the map, which makes it possible to index into aconst map.