4

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 ) ;
  }
}
Community
  • 1
  • 1
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • Or just use iterators again.. – bobobobo Dec 09 '12 at 21:01
  • @BenjaminLindley Some iterators are invalidated when an object is removed but I suppose a list iterator need not be... It's been a while since I actually used lists myself, so I might be absolutely wrong as well . (What a shame you can't downvote comments.) I believe I was thinking that the amount of nodes would matter - but it doesn't have to in a linked list, does it. –  Dec 09 '12 at 21:04
  • @EsaLakaniemi: Might not need to be, and is not allowed to be. That's one of the few redeeming qualities of `std::list`. – Benjamin Lindley Dec 09 '12 at 21:05
  • I'll just remove that comment as misinformation, then. –  Dec 09 '12 at 21:06
  • 5
    @BenjaminLindley - Range based for does use iterators. The iterator for the current position is being invalidated by the remove because it now points at a list node that's gone bye-bye. It will then try to access "next" and nasal demons have been summoned! That is of course assuming that the element being actually removed is the one the user intends...which is not guaranteed in this code. – Edward Strange Dec 09 '12 at 21:06

2 Answers2

5

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 function remove iterates through all elements of a list and removes ones equal to value.

Leonid Volnitsky
  • 8,854
  • 5
  • 38
  • 53
-5

I would just enter your code into a compiler and see if it works.

user_x42475656
  • 26
  • 1
  • 1
  • 7