Maverik
Maverik

Reputation: 2398

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

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:

None of them satisfy my necessity.

Upvotes: 8

Views: 5762

Answers (3)

Hongbo Liu
Hongbo Liu

Reputation: 3054

Currently, could use contains to check whether element exist.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476960

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.

Upvotes: 20

micheal.yxd
micheal.yxd

Reputation: 128

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
}

Upvotes: 0

Related Questions