简体   繁体   中英

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;
        }
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM