Possible Duplicate:
Erasing an element from a container while inside a range-based for loop
Similar to this, can you delete from an STL list while iterating over it using the new for( auto item : list ) syntax?
Here’s a complete example (that crashes!)
#include <list>
using namespace std ;
int main()
{
list<int> li;
li.push_back( 4 ) ;
li.push_back( 5 ) ;
li.push_back( 6 ) ;
for( auto num : li )
{
if( num == 5 )
li.remove( num ) ;
else
printf( "%d\n", num ) ;
}
}
No, you can not. Your example crashes because you use
li.remove(num)incorrectly and internal for-loop iterator is invalidated.li.remove(num)should be used not in loop but as standalone statement. List member functionremoveiterates through all elements of a list and removes ones equal to value.