当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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 ?

网友答案:

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";
}
网友答案:

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";
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: