I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted.
My code goes as follows:
if( ! m_Container.empty() ) { for( typedefedcontainer::iterator it = m_Container.begin(); it != m_Container.end(); ++it ) { if( ! ( SomeFunction( (*it), 'test', 'TEST!', false )) ) { // If function returns false, delete object. m_Container.erase( it ); AsyncResponseStore::iterator it = m_asyncResponses.begin(); } } }
But of course, when I erase an object I get an error : ‘Map / set iterator not incrementable’. Can someone suggest a better way of doing this?
See: What happens if you call erase() on a map element while iterating from begin to end?
It depends on the container. The list container supports deletion during enumeration by returning a new iterator from the erase method that represents the next item in the list. map doesn’t support this.
A simple method for map is to accumulate the items you want to erase in a separate list, and then iterate over that list when you have finished processing the map to erase the items from the map. This assumes that you can defer the deletion until the iteration has completed. If not then you have no choice but the restart the iteration for each deletion.