J
Jim Langston
Someone is working on some code, and during the iteration of a vector may
delete an element and push_back a new one. I was thinking that this may
invalidate the iteration iterator, but in my test it doesn't seem to. Here
is my test with the expected output of:
0 1 2 3 4 5
0 1 3 4 5 6
0 1 4 5 6 7
0 1 5 6 7 8
0 1 6 7 8 9
Is this just luck or is it defined behavior? That is, can push_back
invalidate an existing vector iterator? (In my code it would be it )
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> MyVector;
int Value;
for ( Value = 0; Value < 5; ++Value )
MyVector.push_back( Value );
for ( int i = 0; i < 5; ++i )
{
int Count = 0;
for ( std::vector<int>::iterator it = MyVector.begin(); it !=
MyVector.end(); )
{
std::cout << *it << " ";
if ( Count++ == 2 )
{
it = MyVector.erase( it );
MyVector.push_back( Value++ );
}
else
++it;
}
std::cout << std::endl;
}
std::string wait;
std::getline( std::cin, wait );
return 0;
}
delete an element and push_back a new one. I was thinking that this may
invalidate the iteration iterator, but in my test it doesn't seem to. Here
is my test with the expected output of:
0 1 2 3 4 5
0 1 3 4 5 6
0 1 4 5 6 7
0 1 5 6 7 8
0 1 6 7 8 9
Is this just luck or is it defined behavior? That is, can push_back
invalidate an existing vector iterator? (In my code it would be it )
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> MyVector;
int Value;
for ( Value = 0; Value < 5; ++Value )
MyVector.push_back( Value );
for ( int i = 0; i < 5; ++i )
{
int Count = 0;
for ( std::vector<int>::iterator it = MyVector.begin(); it !=
MyVector.end(); )
{
std::cout << *it << " ";
if ( Count++ == 2 )
{
it = MyVector.erase( it );
MyVector.push_back( Value++ );
}
else
++it;
}
std::cout << std::endl;
}
std::string wait;
std::getline( std::cin, wait );
return 0;
}