C ++:从地图中删除迭代器,然后递增到下一个迭代器

时间:2012-01-11 22:12:22

标签: c++ iterator stdmap allegro

此方法导致中止错误:"map/set iterator not incrementable." 由于在if失败并且确定了应该擦除的虚拟迭代器(并且是)后,通过++_iter继续到地图中的下一个迭代器失败,因为_iter不是更长的有效对象/指针。

迭代地图并能够删除整个项目的正确程序是什么?

typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;
\\...
void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ++_iter) {
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false) continue;
        }
        _cache.erase(_iter);
    }
}

4 个答案:

答案 0 :(得分:6)

你必须要小心一点:

void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false)
            {
                ++_iter;
                continue;
            }
        }

        _cache.erase(_iter++);
    }
}

答案 1 :(得分:2)

map::erase(iterator)为您提供一个迭代器,指向擦除后映射中的下一个元素(如果有的话)。因此,您可以这样做:

for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
    if(_iter->second != NULL) {
        if((_iter->second->w < 0 && _iter->second->h < 0) == false) {
           ++_iter;
           continue;
        }
    }
    _iter = _cache.erase(_iter);
}

答案 2 :(得分:1)

关联容器的标准擦除循环:

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
    if (delete_condition)
    {
        m.erase(it++);
    }
    else
    {
        ++it;
    }
}

答案 3 :(得分:0)

在迭代期间安全擦除迭代器的规范方法是使用container::erase的结果:

void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    MapStrBmpIter _iter = _cache.begin();
    while (_iter != _cache.end()) {
        bool erase_entry= true;
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false) 
                erase_entry= false;
        }

        if (erase_entry)
            _iter= _cache.erase(_iter);
        else
            ++_iter;
    }
}