简体   繁体   中英

How to modify the value of a key-value Pair from a map while I do not know whether the key is exist in the map?

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!!!

If you are going to set the value whether it exists or not, go ahead and use the subscript operator:

a[5] = " G ";

It will create a new mapping if one didn't exist. This is guaranteed by the C++ standard.

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 5 is not present as a key in the map, after you do a[5] it will exist and be associated to an empty string.

C++11 added a new at method that throws if the key does not exist in the map, which makes it possible to index into a const map .

In the example with find() you can modify the value via the returned iterator:

pos->second = " G ";

You should use this approach if you only want to modify if it already exists as the operator[] will create a new entry if it does not currently exist. If you want to add it or modify it, use operator[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM