2013-06-25 18 views
0

我想要std::map insert()功能不同的行爲取決於對插入是否已經在地圖上或不 - 如果不是,將其插入像往常一樣,如果它已經存在,增加存儲在second裏的櫃檯的一對。我怎麼能做到這一點,沒有額外的查詢存在(因爲無論如何插入查詢)?如何實現不同'的std ::地圖插入()`取決於對存在的行爲被插入?

我在跟蹤大量的事件記錄,其中每個記錄都包含sourcereceiver ID。事件存儲爲std::vector。我也想保持sourcesreceivers記錄的字典作爲std::map其中對(密鑰)的first包含了ID,而second包含一些source信息加std::vector跟蹤所有引用該source的事件。

所以,當該事件是指目前不在source,插入應正常進行,但如果稱爲source已經在字典中,插入應的參照事件號碼添加到現有的字典元件的std::vector

回答

1

看起來像一個必須保持insert函數的結果,對其進行分析和相應的行爲:

typedef std::map<int, T> itmap; 
typedef std::pair<itmap::iterator, bool> itinsresult; 
//... 
itmap m; 
int i; 
T t; 
//... 
itinsresult result = m.insert(std::make_pair(i, t)); 
if (result.second) // new element inserted 
{ 
    //... 
} 
else // element already exists 
{ 
    (*result.first).do_something(); 
    // ... 
} 
+1

' - >'添加到語言尤其是避免迂迴'(* result.first).do_something ()' – Slava