Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pop_back() really invalidate *all* iterators on an std::vector?

Tags:

c++

stl

std::vector<int> ints;

// ... fill ints with random values

for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
    if(*it < 10)
    {
        *it = ints.back();
        ints.pop_back();
        continue;
    }
    it++;
}

This code is not working because when pop_back() is called, it is invalidated. But I don't find any doc talking about invalidation of iterators in std::vector::pop_back().

Do you have some links about that?

like image 478
acemtp Avatar asked Sep 15 '08 12:09

acemtp


1 Answers

The call to pop_back() removes the last element in the vector and so the iterator to that element is invalidated. The pop_back() call does not invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":

Inserting or removing elements invalidates references, pointers, and iterators that refer to the following element. If an insertion causes reallocation, it invalidates all references, iterators, and pointers.

like image 70
Ben Avatar answered Oct 05 '22 23:10

Ben