2

此方法会导致中止错误:"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

4 回答 4

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++);
    }
}
于 2012-01-11T22:15:45.967 回答
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);
}
于 2012-01-11T22:19:42.587 回答
1

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

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
    if (delete_condition)
    {
        m.erase(it++);
    }
    else
    {
        ++it;
    }
}
于 2012-01-11T22:19:08.790 回答
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;
    }
}
于 2012-01-11T22:19:34.283 回答