std::map - 元素访问无异常且无插入
我有一个使用 std::map 的循环模式.
I have a recurrent pattern with the use of std::map.
我只想在键存在时检索值,否则我不想插入元素.目前我正在使用 count(key)
或 find(key)
(哪个更好?从文档中,复杂性似乎相同),如果它们返回一个我访问地图的正值.但是我想避免在地图上使用两个操作.类似的东西:
I want to retrieve the value only when the key is present, otherwise I don't want to insert element. Currently I'm using count(key)
or find(key)
(which one is better? from the documentation the complexity seems to be the same) and if them returns a positive value that I access the map. However I would like to avoid the use of two operations on the map. Something like:
map<string, int> myMap;
int returnvalue;
boole result = myMap.get("key1",returnValue)
if(result){
\\ use returnValue
}
阅读关于 cplusplus.com 的 std::map 文档,我发现了两个函数用于访问地图元素:
Reading the std::map documentation on cplusplus.com I found two functions for accessing map elements:
- at(): which throws an excpetion if the key is not present
- []: which insert a new value if the key is not present
没有一个能满足我的需要.
None of them satisfy my necessity.
使用 地图::查找:
auto it = myMap.find(key);
if (it != myMap.end())
{
// use it->second
}
else
{
// not found
}
这部分很简单.更难的问题是当你想查找一个元素是否存在并在它存在时返回它,否则在那个键上插入一个新元素,所有这一切都不需要搜索地图两次.为此,您需要使用 lower_bound
后跟提示插入.
This part was easy. The harder problem is when you want to look up if an element exists and return it if it does, but otherwise insert a new element at that key, all without searching the map twice. For that you need to use lower_bound
followed by hinted insertion.