2013-04-23 30 views
1

我有boost::unordered_map<int, Animal*>,我需要刪除所有的插入其中value就像Animal* a;相同的指針(一個給出動物*像參數,我有不同的密鑰在地圖中同樣動物*對夫婦地方的指針) 。如何從地圖中刪除具有相同值但密鑰不同的所有記錄?

boost::unordered_map<int, Animal*> mp; 
Animal* rex = new Animal("Rex"); 
mp[1]=rex; 
mp[2]=rex; 
mp[9]=rex; 

如何刪除值爲rex的所有記錄,然後從堆中刪除rex一次?

+1

由於地圖是單向(鍵值)優化的。在你的情況下,你必須迭代所有項目並逐個刪除它們。 – deepmax 2013-04-23 11:19:11

回答

5

您需要遍歷列表並刪除與正在搜索的指針值相匹配的記錄。

typedef boost::unordered_map<int, Animal*> AnimalMap; 
AnimalMap mp; 

void DeleteStuff(Animal* searchPointerValue) 
{ 
    for(AnimalMap::iterator it = mp.begin(); it < mp.end();) 
    { 
     if(it->second == searchPointerValue) 
     { 
      // erase() invalidates the iterator but returns a new one 
      // that points to the next element in the map. 
      it = mp.erase(it); 
     } 
     else 
     { 
      ++it; // Only bump the iterator if no erase is done 
        // since unordered_map::erase() takes care of that for us 
     } 
    } 

    // now we can delete the animal as you so desire 
    delete searchPointerValue; 
} 
+0

這將導致內存泄漏 - 沒有'刪除'動物*' – 2013-04-23 11:23:04

+0

@Kiril我們看不到他們是如何創建的,誰知道他們應該如何刪除? – 2013-04-23 11:27:03

+0

@PeterWood - 你是什麼意思?它在問題中顯示:'Animal * rex = new Animal(「Rex」);' – 2013-04-23 11:29:08

2

使用智能指針,如boost::shared_ptr,而不是原始指針。這將使您有機會從地圖中刪除元素,而不用擔心。

有一個帶引用計數的智能指針,您可以簡單地遍歷地圖並擦除每個具有所需值的元素。

2
typedef boost::unordered_map<int, Animal*> mapType; 
mapType myMap; 

mapType::iterator it = myMap.begin(); 
while(it != myMap.end()) 
{ 
    if(it->second == current_pointer) 
     it = mp.erase(it); 
    else 
     ++it; 
} 

delete current_pointer; // Don't forget this 
0

如何使用std::remove_if與合適的函子?

std::remove_if(std::begin(mp), std::end(mp), 
       [](const std::pair<int, Animal*>& pair) 
       { return (pair.second == rex); }); 

當然這可能會導致內存泄漏,除非你做delete rex。使用smart pointers是個好主意。

+0

根據[cpp參考](http://en.cppreference.com/w/cpp/algorithm/remove),不可能在關聯容器中使用remove_if。 – 2015-06-12 08:32:27

相關問題