Search code examples
c++debuggingvectoriteratorrogue-wave

Vector iterators incompatible: DEBUG


Why is this piece of code giving me the error : Vector iterators incompatible

This piece of code was traced back to the Rogue Wave file tpordvec.h

    std::vector<T*> v;
    const T* a  // Where T is a template Class 
    for (std::vector<T*>::iterator p = v.begin(); p != v.end(); p++)
    {
        if (**p == *a)
        {
            T* temp = *p;
            if ( v.erase(p) == v.end()) //ASSERTION ERROR HERE
               return NULL;

            return temp;
        }
    }

Solution

  • http://en.cppreference.com/w/cpp/container/vector/erase

    Iterators and references to the erased elements and to the elements between them and the end of the container are invalidated. The past-the-end iterator is also invalidated.

    Hence if the vector.end() is evaluated before the vector.erase() and vector.erase() really erases and by doing so invalidates the iterators till end(), the call to operator==() will be between two incompatible iterators.

    Something like this would be better:

    auto it = v.erase(p); 
    if ( it == v.end())
    { 
           return NULL;
    }