471,873 Members | 2,031 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Iterator in loop

int main()
std::vector<int> vec;
vector<int>::iterator iter;
for (int i = 0 ; i < 5 ; i++)
for (iter = vec.begin() ; iter != vec.end(); iter++)
if (*iter == 12 || *iter == 13)
for (iter = vec.begin() ; iter != vec.end(); iter++)
printf("%d", *iter);
return 0;

What happens to the iterator when it is incrementedin loop, after erasing 12?

Actually i want to understand the behaviour of the iterator when the element it is pointing to is deleted.
Sep 19 '06 #1
1 14662
293 100+
Straight from the STL 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.
Sep 19 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Scott Smedley | last post: by
9 posts views Thread by Alexander Stippler | last post: by
6 posts views Thread by samuel.y.l.cheung | last post: by
5 posts views Thread by Mark Stijnman | last post: by
18 posts views Thread by silversurfer | last post: by
27 posts views Thread by Steven D'Aprano | last post: by
7 posts views Thread by Max Odendahl | last post: by
reply views Thread by YellowAndGreen | last post: by

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.