我有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一次?
您需要遍历列表并删除与您要搜索的指针值匹配的记录.
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)
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |