Search code examples
c++dictionaryiteratorcontainers

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


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 ?


Solution

  • 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";
    }