質問

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.

役に立ちましたか?

解決

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.

他のヒント

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
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top