Iterator in loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sivayella
    New Member
    • Sep 2006
    • 1

    Iterator in loop

    int main()
    {
    std::vector<int > vec;
    vector<int>::it erator 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.
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    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.

    Comment

    Working...