問題描述
前段時間和同事討論如何在STL中插入值地圖.我更喜歡 map[key] = value;
因為它感覺自然并且清晰易讀,而他更喜歡 map.insert(std::make_pair(key, value))
.
A while ago, I had a discussion with a colleague about how to insert values in STL maps. I preferred map[key] = value;
because it feels natural and is clear to read whereas he preferred map.insert(std::make_pair(key, value))
.
我剛剛問過他,我們都不記得為什么 insert 更好的原因,但我確信這不僅僅是一種風格偏好,而是有一個技術原因,比如效率.SGI STL 參考 簡單地說:嚴格來說,這個成員函數是不必要:它的存在只是為了方便."
I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The SGI STL reference simply says: "Strictly speaking, this member function is unnecessary: it exists only for convenience."
誰能告訴我這個原因,還是我只是在夢想有一個?
Can anybody tell me that reason, or am I just dreaming that there is one?
推薦答案
當你寫作時
map[key] = value;
無法判斷您是否替換了key
的value
,或者您是否創建了一個新的key
和 value
.
there's no way to tell if you replaced the value
for key
, or if you created a new key
with value
.
map::insert()
只會創建:
using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
cout << "key " << key << " already exists "
<< " with value " << (res.first)->second << endl;
} else {
cout << "created key " << key << " with value " << value << endl;
}
對于我的大部分應用,我通常不在乎我是創建還是替換,所以我使用更容易閱讀的map[key] = value
.
For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = value
.
這篇關于在 STL 映射中,使用 map::insert 是否比使用 [] 更好?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!