2014-12-19 60 views
0

如何從源地圖正確查找元素並將其插入另一個地圖?C++地圖,查找元素並將其插入到另一個地圖中(無需複製)

std::map<int, std::shared_prt<Obj>> src_map 
std::map<int, std::shared_prt<Obj>> target_map 

int key = 6; 
auto found_elem = src_map.find(key); 

if (found_elem != src_map.end()) { 
    if (target_map.find(key) == target_map.end()) { 
    target_map.insert(found_elem); <---- How to correctly insert found element from src_map to target_map 
    } 
} 
+3

沒有複製,除非你使用像'std :: map > src_map;'這樣的東西。 – 2014-12-19 10:43:51

+1

「沒有複製」 - 所以你想從'src_map'中刪除它? – 2014-12-19 10:44:14

+0

我的對象這是指針,我不需要複製對象。我不需要從src_map中刪除elem。 – Yuri 2014-12-19 10:46:38

回答

5
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; 
+2

'target_map.insert(* found_elem);'就夠了。然後,您仍然可以檢查返回的對在哪裏以及是否插入了該元素。 – Jarod42 2014-12-19 11:01:50

+0

非常好的一點! – 2014-12-19 11:04:39

0

在當前聲明

std::map<int, Obj> src_map 
std::map<int, Obj> target_map 

你不能有一個的OBJ比如在連接到這兩個地圖的記憶。您可以從src_map中刪除Obj並將target_map或更改聲明更改爲;

std::map<int, Obj*> src_map 
std::map<int, Obj*> target_map 

或任何其他指針類型(如評論所說的shared_ptr),如果沒有這個,你將永遠在記憶兩個獨立的對象。

相關問題