2

I have boost::unordered_map<int, Animal*> and I need to delete all inserts where value is the same pointer like Animal* a; ( a is given Animal* like parameter, I have for different keys in map same Animal* pointer on couple places).

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

How to delete all records where value is rex, and after that delete rex from heap only once ?

4

4 回答 4

6

您需要遍历列表并删除与您正在搜索的指针值匹配的记录。

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;
}
于 2013-04-23T11:19:27.517 回答
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
于 2013-04-23T11:23:53.803 回答
2

使用智能指针,如boost::shared_ptr,而不是原始指针。这将使您有机会毫无顾虑地从地图中删除元素。

拥有一个带有引用计数的智能指针,您可以简单地遍历映射并擦除每个具有您想要的值的元素。

于 2013-04-23T11:21:31.167 回答
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。使用智能指针是个好主意。

于 2013-04-23T11:25:36.950 回答