468,513 Members | 941 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

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 14575
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
By using this site, you agree to our Privacy Policy and Terms of Use.