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 ?
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.
}
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With