在C ++ 11的unordered_map中,如何更新特定键的值? [英] In unordered_map of C++11, how to update the value of a particular key?
问题描述
在Java的hashmap中:
map.put(key,new_value)
如果hashmap中存在key =在C ++ 11的unordered_map中做类似的事情的正确方法是什么?
我没有找到像updateXXX这样的API,
解决方案如果没有任何这样的对,则unordered_map :: insert 你知道键在地图中,你可以使用
operator []
,它返回对映射值的引用。因此,它将map [key] = new_value
。但是,请注意,如果地图中不存在该键,则会插入(key,new_value)
。
您还可以使用
find
,它返回一个迭代器的值:auto it = map.find(key)
if(it!= map.end())
it-> second = new_value;
In Java's hashmap:
map.put(key, new_value)
will update the entry of key=key with new_value if it exists in the hashmap.
What's the correct way to do the similar thing in unordered_map of C++11?
I haven't found an API like updateXXX, and the documentation says the unordered_map::insert function will succeed only when there isn't any such pair with a key.
解决方案If you know that the key is in the map, you can utilize
operator[]
which returns a reference to the mapped value. Hence it will bemap[key] = new_value
. Be careful, however, as this will insert a(key, new_value)
if the key does not already exist in the map.You can also use
find
which returns an iterator to the value:auto it = map.find(key) if(it != map.end()) it->second = new_value;
这篇关于在C ++ 11的unordered_map中,如何更新特定键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!