I read in The C++ Programming Language : Special Edition
Don't use iterators into a resized vector
Consider this example.
vector< int >::iterator it = foo.begin();
while ( it != foo.end() ) {
if ( // something ) {
foo.push_back( // some num );
}
++it;
}
Is there a problem with this? After the vector was resized, would the foo.end() in the loop condition be pushed forward 1?
P.S. In addition, what if vector had reserved space for x number of ints. If push_back didn’t violate this space, would it still be an issue ( I would assume so if it.end() points to one past the last element in the vector that contains something ).
Yes, there is a problem with it.
Any call to
push_backhas the potential to invalidate all iterators into a vector.foo.end()will always retrieve the valid end iterator (which may be different to the value last returned byfoo.end()), butitmay have been invalidated. This means that incrementing it or comparing it may caused undefined behaviour.