make_pair of std::map - how to make a pair only if the key is not listed (and update the key otherwise)?

36,004

Solution 1

Add a condition before insert

if (myMap.find("first_key") == myMap.end()) {
  myMap.insert(std::make_pair("first_key" , "first_value" ));
}
else {
  myMap["first_key"] = "first_value";
}

Solution 2

Use operator [], or use find and change value if key finded. Will insert pair in map, if there is no such key and update value, if key exists.

myMap["first_key"] = "first_value";

Or this:

auto pos = myMap.find("first_key");
if (pos != myMap.end())
{
   pos->second = "first_value";
}
else
{
   // insert here.
}

Solution 3

It's more efficient to avoid searching the map a second time when the value is present:

const iterator i = myMap.find("first_key");
if (i == myMap.end()) {
    myMap.insert(std::make_pair("first_key" , "first_value"));
} else {
    i->second = "first_value";
}
Share:
36,004
JAN
Author by

JAN

The biggest C# and JAVA enthusiastic ever existed.

Updated on July 09, 2022

Comments

  • JAN
    JAN almost 2 years

    Consider the following code :

    std::map <string,string> myMap;
    myMap.insert(std::make_pair("first_key" , "no_value" ));
    myMap.insert(std::make_pair("first_key" , "first_value" ));
    myMap.insert(std::make_pair("second_key" , "second_value" ));
    
    typedef map<string, string>::const_iterator MapIterator;
    for (MapIterator iter = myMap.begin(); iter != myMap.end(); iter++)
    {
        cout << "Key: " << iter->first << endl << "Values:" << iter->second << endl;
    }
    

    The output is :

    Key: first_key
    Values:no_value
    Key: second_key
    Values:second_value
    

    Meaning is that the second assignment :

    myMap.insert(std::make_pair("first_key" , "first_value" ));
    

    didn't take place .

    How can I make a pair , only if the key is not already listed , and if is listed - change its value ?

    Is there any generic method of std::map ?