Quote:Original post by Anonymous Poster
"2) the iterator "it" is invalidated after erasure, along with all iterators after it."
As far as I can see in my cpp-reference, erase() only calls delete for the object that the pointer points to and then clears the pointer.
Quote:From SGI's std::vector documentation:
[5] A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end.
Can't seem to find similar warning in the MSDN. Then again, they don't even have a warning about iterator invalidation on resize() in there either (where I'm looking) so I'm not suprised.
Quote:...and there is an example where you iterate through a vector and delete every object.
It's a bad idea preformance-wise on a vector (not so on a list), but is legal C++ with a defined effect if one sets the iterator to the return of erase() (which was not done) - however, erasing an object at an iterator most definately invalidates iterators pointing to that object. Also note that undefined behavior such as this can include "running just like you'd expect/hope" - but it's still best avoided, as this can also include "launching nuclear missiles at a cow ranch in Alaska".
Quote:Anyway, vectors should not be used for dynamic purposes in this way...
Vectors can work just fine if your requirements include checking an entire range for dying elements - a list is prefered if you're going to do random willy nilly erasures( read: erase() a single element at a time ), but that's not what's happening here. The effects of cache-consistancy may very well make the vector version outpreform the list version, especially with POD types such as pointers, in which relocation of the item is a simple O(1) time algorithm consisting of moving a measly 4 bytes. Calling this sequence of remove_if and erase on a single
range is still an O(N) complexity algorithm, just the same as with a list. Doing this with individual erases will be O(N) for lists, O(N*N) for vectors, which is exactly what I'm trying to point out and provide a sound alternative against.