target_map.insert(found_elem);
found_elem
是一個迭代器,你需要插入它指的是值:
target_map.insert(*found_elem);
而且這可以更有效的進行:
if (target_map.find(key) == target_map.end()) {
target_map.insert(found_elem);
}
你做查找兩次。一旦進入find
並再次進入insert
。
最好是剛剛嘗試插入它,如果你需要知道它是否被插入檢查返回值:
auto inserted = target_map.insert(*found_elem);
// inserted.first is the iterator to the element with the desired key
// inserted.second is true if a new element was inserted, false if the key already existed
以便讓你可以在地圖中的其他選項找到位置,在其所屬然後在該位置插入,如果它不是已經存在:
auto lower = target_map.lower_bound(key);
if (lower == target_map.end() || lower->first != key) {
target_map.insert(lower, *found_elem);
}
另一種選擇是:
auto& val = target_map[found_elem->first];
if (!val)
val = found_elem->second;
但這不完全相同,因爲如果密鑰已經存在於地圖中,並且空值shared_ptr
作爲值,則值將被替換。具體取決於地圖中是否可能有空的shared_ptr對象,可能對您的程序不正確。
另一個,再次與略有不同的含義,就是:
target_map[found_elem->first] = found_elem->second;
沒有複製,除非你使用像'std :: map> src_map;'這樣的東西。 –
2014-12-19 10:43:51
「沒有複製」 - 所以你想從'src_map'中刪除它? – 2014-12-19 10:44:14
我的對象這是指針,我不需要複製對象。我不需要從src_map中刪除elem。 – Yuri 2014-12-19 10:46:38