C++ make_pair of std::map - 如何仅在未列出密钥时进行配对(否则更新密钥)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14030162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
make_pair of std::map - how to make a pair only if the key is not listed (and update the key otherwise)?
提问by JAN
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 ?
有没有 std::map 的通用方法?
采纳答案by Haocheng
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";
}
回答by ForEveR
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.
如果找到键operator []
,请使用,或使用find
并更改值。将在地图中插入对,如果没有这样的键和更新值,如果键存在。
myMap["first_key"] = "first_value";
Or this:
或这个:
auto pos = myMap.find("first_key");
if (pos != myMap.end())
{
pos->second = "first_value";
}
else
{
// insert here.
}
回答by ddiepo
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";
}