如何从地图中删除具有相同值但不同键的所有记录?

Pao*_*aJ. 2 c++ boost stl

我有boost::unordered_map<int, Animal*>,我需要删除所有插入,其中值是相同的指针Animal* a;(一个动物*像参数,我有不同的键在地图相同的动物*指针在几个地方).

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

如何删除值为rex的所有记录,之后只从堆中删除rex一次?

Cap*_*ous 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;
}
Run Code Online (Sandbox Code Playgroud)