make_pair of std :: map - 如果没有列出密钥,如何建立一对(否则更新密钥)?

JAN*_*JAN 3 c++ containers iterator map

请考虑以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Key: first_key
Values:no_value
Key: second_key
Values:second_value
Run Code Online (Sandbox Code Playgroud)

意思是第二个任务:

myMap.insert(std::make_pair("first_key" , "first_value" ));
Run Code Online (Sandbox Code Playgroud)

没有发生.

我怎样才能成对,只有当密钥尚未列出时,如果列出了 - 更改其值?

是否有std :: map的通用方法?

For*_*veR 5

如果密钥有效operator [],请使用或使用find和更改值.如果没有这样的密钥和更新值,如果密钥存在,将在映射中插入对.

myMap["first_key"] = "first_value";
Run Code Online (Sandbox Code Playgroud)

或这个:

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


小智 5

当值存在时,避免再次搜索地图会更有效:

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";
}
Run Code Online (Sandbox Code Playgroud)