简体   繁体   English

我可以使用std :: vector.size()来控制要删除元素的循环吗?

[英]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 我已经在其他可能存在问题的部分上创建了该线程: 堆损坏试图向现有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). 您的循环正常(假设iNeedToRemoveThisElement不会做任何不好的事情)。 The loop condition is executed every time, so you always compare with the current vector.size() reflecting the latest updates. 每次都执行循环条件,因此您总是将其与反映最新更新的当前vector.size()进行比较。

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. 此外,仔细检查循环还会发现您没有陷入比较的另一个潜在陷阱:如果i为负,则比较会vector.size() false因为vector.size()是无符号的。 However it turns out that at the time of comparison, i is never negative. 但是事实证明,在进行比较时, i永远不会为负。

There is one caveat where I'm not completely sure: If i refers to the last element, you swap that element with itself; 有一个需要我不确定的警告:如果i指的是最后一个元素,则将其与自身交换; 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). 我不确定这是否是定义的行为(对于C ++ 98 / C ++ 03复制实现,当然没有问题,但是我不确定C ++ 11 move实现是否也支持它)。 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. 更新:正如dyp在评论中解释的那样,允许自动交换,因此无需特殊情况。

In any case, you should look up the algorithms std::remove and std::remove_if from the C++ standard library. 无论如何,您应该从C ++标准库中查找算法std::removestd::remove_if 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. 它们使您可以完全摆脱循环,如果您可以使用C ++ 11的lambda函数,它也比循环更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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