std::map - Element access without exception and without insertion

a 夏天 提交于 2019-12-13 01:26:38

问题


I have a recurrent pattern with the use of std::map.

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
}

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.


回答1:


Use map::find:

auto it = myMap.find(key);

if (it != myMap.end())
{
    // use it->second
}
else
{
    // not found
}

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.




回答2:


using count() for sure the key is exists then uses find() to get the k/v pair

if (myMap.count(key))
{
    auto it = myMap.find(key)
}
else
{
// not found
}


来源:https://stackoverflow.com/questions/19290780/stdmap-element-access-without-exception-and-without-insertion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!