Incorrect behaviour with vector::erase( vector<T>::iterator ) ?
Jeroen Dobbelaere
Jeroen.Dobbelaere@tvd.be
Wed Mar 31 23:54:00 GMT 1999
Hi,
I think your code contains a bug :
Taking a look a note 5 on :
< http://www.sgi.com/Technology/STL/Vector.html >
--
[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.
--
My guess is that the iterator doom->where is not valid any more after one of the other insertions.
(It can point to something that looks valid (the value of (*(doomed->where))->junk is what we would
expect),
but isn't (the object to which it points doesn't belong any more to the current 'vec'))
I can't try it out right now, but you could try adding 'vec.reserve(20)' after the declaration of vec.
Greetings,
Jeroen Dobbelaere
Michael K Vance wrote:
>
> Output on g++-2.8.1:
>
> 13
> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
>
> Output on egcs-1.1.2:
>
> 13
> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
> 1 2 3 4 134527404 134527408 134527412 134528056 134528060 134528064 134528068
> 134528072 134528076 134528080 134528084 134528952 17 18 19
>
> These both seem incorrect, though the g++-2.8.1 seems at least a little more
> correct. Am I missing something here?
>
> Thanks,
>
> m.
>
> --
>
> #include <vector>
>
> class Bob
> {
> public:
> int junk;
> vector<Bob*>::iterator where;
>
> Bob( int i ) : junk( i ) { };
> };
>
> int main( void )
> {
> vector<Bob*> vec;
> Bob* doomed;
>
> for( int i = 0; i < 20; i++ ) {
> Bob* b = new Bob( i );
> vector<Bob*>::iterator where = vec.insert( vec.end( ), b );
> b->where = where;
>
> if( i == 13 ) {
> doomed = b;
> }
>
> }
>
> cerr << (*(doomed->where))->junk << endl;
>
> for( int i = 0; i < 20; i++ ) {
> cerr << vec[i]->junk << " ";
> }
>
> vec.erase( doomed->where );
> cerr << endl;
>
> for( int i = 0; i < 19; i++ ) {
> cerr << vec[i]->junk << " ";
> }
>
> cerr << endl;
>
> return 0;
> }
>
> --
> "We can deny everything, except that we have the possibility of being better.
> Simply reflect on that."
> -- His Holiness The Dalai Lama
More information about the Gcc-bugs
mailing list