请考虑以下代码:
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;
}
输出结果为:
Key: first_key
Values:no_value
Key: second_key
Values:second_value
意思是第二个任务:
myMap.insert(std::make_pair("first_key" , "first_value" ));
没有发生。
如果尚未列出密钥,并且列出了密钥,我该如何成对呢?更改其值?
是否有std :: map的通用方法?
答案 0 :(得分:5)
使用operator []
,或使用find
并在密钥查找时更改值。
如果没有这样的密钥和更新值,如果密钥存在,将在映射中插入对。
myMap["first_key"] = "first_value";
或者这个:
auto pos = myMap.find("first_key");
if (pos != myMap.end())
{
pos->second = "first_value";
}
else
{
// insert here.
}
答案 1 :(得分:4)
在插入
之前添加条件if (myMap.find("first_key") == myMap.end()) {
myMap.insert(std::make_pair("first_key" , "first_value" ));
}
else {
myMap["first_key"] = "first_value";
}
答案 2 :(得分:2)
当值存在时,避免第二次搜索地图会更有效:
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";
}