I was wondering if something like that is safe ...
// Iterating through a <list> while ( iter != seq.end()) { if ( test ) { iter = seq.erase( iter ); } else { ++iter; }
I know that iterating through a vector this way will invalidate the iterator, but will it happen on the list? I assume that since the list is sequential with pointers and not “next to” each other in memory, but any reassurance would be helpful.
This is just fine, because the erase method returns a new valid iterator.
Yes, this is the standard way to do this. See “Effective STL”, paragraph 9 (page 46).
- std::list::erase(): " ".
std::list::erase()
, , , - , , std::remove_if().
std::remove_if()
erase STL. std::list . erase , ( list.end()).
erase
std::list
list.end()
, , :
.. it = l.begin(); while(it != l.end()) { it = l.erase(it); }
- ( ):
for (.. it = l.begin; it != l.end(); ++it) { it = l.erase(it); }
l.end(), ( ). Baamm.
l.end()
, . erase() , , . erase() iter, .
erase()
iter
As others have explained, your code does not invalidate the iterator used in this function. However, it invalidates other iterators if the collection is a vector, but not if the collection is a list.
As others have said, yes, it will work. But I recommend using list :: remove_if instead , as this is more expressive.