By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 816 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

Iterator in loop

P: 1
int main()
{
std::vector<int> vec;
vector<int>::iterator iter;
for (int i = 0 ; i < 5 ; i++)
{
vec.push_back(i+10);
}
for (iter = vec.begin() ; iter != vec.end(); iter++)
{
if (*iter == 12 || *iter == 13)
{
vec.erase(iter);
}
}
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
Share this Question
Share on Google+
1 Reply


100+
P: 293
D_C
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.