简体   繁体   中英

Vector.end() unexpected behavior after deleting an element in C++

I'm facing a problem when I delete duplicate values in a vector. I know that when a vector value gets deleted the vector gets re-allocated for maintaining the data without any "dark holes". The problem is that when I'm using remove() inside a loop, when the code runs back to the condition statement of it, I get an assertion failed message.

My question is: if I'm using nums.end() at a condition for the iteration, does it get a static value of an iterator, or for each iteration it returns a new iterator that points to the end of the new re-allocated vector? If it does or if not, what seems to be wrong with the incrementation?

while ( itfast != nums.end()) {
        if (*itslow == *itfast) {
            nums.erase(itfast);
        }
        else {
            itslow++;
            itfast++;
        }
    }

std::vector.erase invalidates the current iterator, but returns an iterator pointing to the next valid iterator passed the one erased.

itfast = nums.erase(itfast);

As Daniel pointed out, this will invalidate any other iterator you have so you must handle the itslow case as well.

When dealing with more complicated erasing it can be much simpler and less error prone to deal with indices instead, though there are also pitfalls regarding itslow if you remove an element and itslow >= removed element. Without seeing what your exact problem is I can't say precisely which to use.

Please see the cppreference for more details regarding erase. There are also several other questions very similar to this.

https://en.cppreference.com/w/cpp/container/vector/erase std::vector iterator invalidation

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