Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdmap

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.

like image 420
Maverik Avatar asked Oct 10 '13 08:10

Maverik


1 Answers

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.

like image 122
Kerrek SB Avatar answered Nov 04 '22 04:11

Kerrek SB