【问题标题】:How to delete from map all records with same value but different keys?如何从映射中删除具有相同值但不同键的所有记录?
【发布时间】:2013-04-23 11:16:49
【问题描述】:

我有boost::unordered_map<int, Animal*>,我需要删除所有插入值与Animal* a; 相同的指针( a 被赋予 Animal* 类似的参数,我有对于地图中的不同键,在几个地方有相同的 Animal* 指针)。

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

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

【问题讨论】:

  • 因为地图是单向优化的(key-to-value)。在您的情况下,您必须遍历所有项目并逐一删除它们。

标签: c++ boost stl


【解决方案1】:

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

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;
}

【讨论】:

  • 这会导致内存泄漏 - 没什么 deletes Animal*
  • @Kiril 我们看不到它们是如何创建的,谁知道应该如何删除它们?
  • @PeterWood - 你是什么意思?它显示在问题中:Animal* rex = new Animal("Rex");
  • @CaptainObvlious - "如何删除值为 rex 的所有记录,之后只从堆中删除 rex 一次"
  • @Kiril 我的意思是答案,而不是问题。我想我们现在都清楚了(c:
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      【解决方案4】:

      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 是个好主意。

      【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多