Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 260
JAN Avatar asked Dec 11 '22 19:12

JAN


2 Answers

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.
}
like image 182
ForEveR Avatar answered May 19 '23 17:05

ForEveR


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";
}
like image 43
ddiepo Avatar answered May 19 '23 19:05

ddiepo