簡體   English   中英

make_pair of std :: map - 如果沒有列出密鑰,如何建立一對(否則更新密鑰)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM