简体   繁体   中英

Can I use std::vector.size() to control a loop that's removing elements?

I have a big headache in a object detector I'm working on.
I have already created this thread about other part that could be the problem: Heap Corruption trying to add elements to existing std::vector

But, now, I'm thinking maybe the way I remove elements from a vector might be my problem. So, simple question, can i do something like this...

for (int i=0; i < vector.size(); i++){
    if(iNeedToRemoveThisElement){
        std::swap(vector[i],vector.back());
        vector.pop_back();
        i--;
    }

?

Your loop is OK (assuming iNeedToRemoveThisElement does not do anything bad, of course). The loop condition is executed every time, so you always compare with the current vector.size() reflecting the latest updates.

Also, a careful examination of the loop also reveals that you don't fall into the other potential pitfall of the comparison: If i is negative, the comparison would give false because vector.size() is unsigned. However it turns out that at the time of comparison, i is never negative.

There is one caveat where I'm not completely sure: If i refers to the last element, you swap that element with itself; I'm not sure whether that is defined behaviour (with the C++98/C++03 copy imlementation, there's of course no problem, but I'm not sure whether the C++11 move implementation also supports it). So it might be needed to special-case this. Update: As dyp explains in the comments, self-swap is allowed, so there's no need to special-case for it.

In any case, you should look up the algorithms std::remove and std::remove_if from the C++ standard library. They allow you to get rid of the loop completely, and if you can use C++11's lambda functions, it's also simpler than the loop.

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