![](/img/trans.png)
[英]std::make_pair, std::unordered_map and usage of move constructor from key type
[英]make_pair of std::map - how to make a pair only if the key is not listed (and update the key otherwise)?
請考慮以下代碼:
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的通用方法?
使用operator []
,或者如果鍵有效,則使用find
和更改值。 如果沒有這樣的密鑰和更新值,如果密鑰存在,將在映射中插入對。
myMap["first_key"] = "first_value";
或這個:
auto pos = myMap.find("first_key");
if (pos != myMap.end())
{
pos->second = "first_value";
}
else
{
// insert here.
}
插入前添加條件
if (myMap.find("first_key") == myMap.end()) {
myMap.insert(std::make_pair("first_key" , "first_value" ));
}
else {
myMap["first_key"] = "first_value";
}
當值存在時,避免第二次搜索地圖會更有效:
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.