473,407 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Does .push_back invalidate existing vector iterators?

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<intMyVector;

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;
}
Jan 6 '07 #1
10 6320
Jim Langston wrote:
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 )
It will, if the vector needs to re-allocate, that is, if before the
push_back() call, size()==capacity().
Jan 6 '07 #2

Jim Langston wrote:
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 )
Increasing the number of items in a vector (by whatever means or by
whatever number) may invalidate the vector's iterators only if the
addition of the item (or items) cause the vector's size to exceed its
current capacity.

Since your program first removes an item before adding one, the size of
the vector never increases beyond its initial size during the course of
the operation. So there is no risk of the vector's capacity being
exceeded and consequently no danger that any of the vector's iterators
will be invalidated.

Greg

Jan 6 '07 #3
Jim Langston wrote:
...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?
It was just luck. In C++ you should *NEVER* make
assumptions based on "well, it seems to work...".

can push_back invalidate an existing vector iterator?
Yes - see other replies for the reasons why.
--
<\___/>
/ O O \
\_____/ FTB. For email, remove my socks.
We’re judging how a candidate will handle a nuclear
crisis by how well his staff creates campaign ads.
It’s a completely nonsensical process.
Jan 6 '07 #4
"Jim Langston" <ta*******@rocketmail.comwrote in message
news:bf***************@newsfe02.lga...
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<intMyVector;

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;
}
Thanks for the answers everyone. So as long as capacity() doesn't change,
the allocatore is valid.

Thanks.
Jan 6 '07 #5

Jim Langston wrote:
"Jim Langston" <ta*******@rocketmail.comwrote in message
news:bf***************@newsfe02.lga...
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<intMyVector;

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;
}

Thanks for the answers everyone. So as long as capacity() doesn't change,
the allocatore is valid.

Thanks.
Yeah... but you probably want to program defensively and always assume
that the iterator will be invalidated

Jan 6 '07 #6
"bjeremy" <bj*****@sbcglobal.netwrote in message
news:11**********************@q40g2000cwq.googlegr oups.com...
>
Jim Langston wrote:
>"Jim Langston" <ta*******@rocketmail.comwrote in message
news:bf***************@newsfe02.lga...
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<intMyVector;

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;
}

Thanks for the answers everyone. So as long as capacity() doesn't
change,
the allocatore is valid.

Thanks.

Yeah... but you probably want to program defensively and always assume
that the iterator will be invalidated
True, but then the way around this is to use size_t instead of an iterator.
I prefer using iterators because it's much harder to fall off the end of the
vector.
Jan 7 '07 #7

Jim Langston wrote:
True, but then the way around this is to use size_t instead of an iterator.
I prefer using iterators because it's much harder to fall off the end of the
vector.
Interesting. I prefer indices for exactly the same reason :)

Mirek

Jan 7 '07 #8
bjeremy wrote:
Yeah... but you probably want to program defensively and always assume
that the iterator will be invalidated.
So in a nutshell: "programming defensively" is really a two-phase
process: in the first phase the programmer pretends that a catastrophic
bug exists in one of the program's third party libraries, in the second
phase the programmer writes code in the program's own sources to fix
the same imaginary bug in the third party library.

Greg

Jan 8 '07 #9

Greg wrote:
bjeremy wrote:
Yeah... but you probably want to program defensively and always assume
that the iterator will be invalidated.

So in a nutshell: "programming defensively" is really a two-phase
process: in the first phase the programmer pretends that a catastrophic
In nutshell: There is a very limited number of scenarios where
knowledge of iterator not being invalidated by mutating operation would
have any benefit. And there is a very high danger of being shot in the
leg relying on it.

Jan 8 '07 #10

Greg wrote:
bjeremy wrote:
Yeah... but you probably want to program defensively and always assume
that the iterator will be invalidated.

So in a nutshell: "programming defensively" is really a two-phase
process: in the first phase the programmer pretends that a catastrophic
bug exists in one of the program's third party libraries, in the second
phase the programmer writes code in the program's own sources to fix
the same imaginary bug in the third party library.

Greg
No... I'm not sure what you inferred, I don't know where that whole
"catastrophic bug" rant came from, but what I was implying is that you
probably want to try and reduce your problem as to not introduce
special case scenarios. In this case, upon a push_back, the iterator
may or may not be invalid. This is dtermined at a lower layer you have
not control over this (ok...ok... let's not start arguing semantics),
but at your layer you have three choices on how to handle this
situation:
1. Always assume the iterator to be valid - we all can see how this
would be a train wreck waiting to happen
2. Design two cases, one to handle when the iterator is valid, on to
handle when the iterator is invalid. This creates the special case. I'm
sure you are a very competent programmer, as for myself, the more
special cases (or code for that matter) I write, the more chances I
have for introducing new bugs and reducing readability.
3. Always assume the iterator is invalid, and handle every scenario the
same homogenous way...

Jan 8 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: bartek | last post by:
Hi, I'm sorry for asking such a simple question. I just would like to know what's the standard-defined behaviour when doing a push_back() on a std::deque. TIA, b
3
by: codefixer | last post by:
Hello, I am trying to understand if ITERATORS are tied to CONTAINERS. I know the difference between 5 different or 6(Trivial, on SGI). But what I fail to understand is how can I declare all 5...
6
by: pit3k | last post by:
My program tries to call the vector::push_back(...) member function in a loop couple dozen milion times, which is what I expect. After about 20 millions successfull push_back() calls the program...
4
by: Nick Keighley | last post by:
Hi, I've checked out various documentation for multimap but can't find anywhere it explicitly stated that insert() invalidates multimap iterators. consider this pseudo code:- int...
9
by: Someonekicked | last post by:
In my program, I need to open multiple files, and I wont know till after the program execution how many of them (user will enter that value). So I am using a vector of fstream. I am using fstream...
1
by: heng | last post by:
A lot of operations such as erase and popfront will invalidate iterators of vector, however, what will happen to list? Is there any influence to list? Thanks a lot.
3
by: JDT | last post by:
Hi, My understanding about vector's reserve() is to allocate memory for the vector. If so, is it right that each push_back() in the following loop causes no memory reallocation and its...
19
by: Angus | last post by:
I have a socket class CTestClientSocket which I am using to simulate load testing. I create multiple instances of the client like this: for (int i = 0; i < 5; i++) { CTestClientSocket* pTemp...
2
by: Lambda | last post by:
The code is simple: // Token.h #ifndef TOKEN_H #define TOKEN_H #include <vector> #include <string> class Token
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.