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

Cas*_*sey 2 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

ybu*_*ill 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++);
    }
}
Run Code Online (Sandbox Code Playgroud)