C++: Erasing an iterator from a map and then incrementing to the next iterator

3.4k Views Asked by At

This method causes an abort error: "map/set iterator not incrementable." Due to that after the if fails and a vaild iterator that should be erased is determined, (and is), continuing to the next iterator in the map via ++_iter fails because _iter is no longer a valid object/pointer.

What is the correct procedure for iterating through a map AND having the ability to remove individual items throughout?

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

There are 4 best solutions below

5
On BEST ANSWER

You just have to be a bit more careful:

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++);
    }
}
0
On

The standard erase loop for an associative container:

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

The canonical way to safely erase iterators during an iteration is to use the result of 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;
    }
}
2
On

map::erase(iterator) gives you an iterator pointing to the next element in the map (if any) after erasing. Therefore, you can do:

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