简体   繁体   English

删除 C++ 中的元素后的 Vector.end() 意外行为

[英]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.问题是,当我在循环中使用 remove() 时,当代码运行回它的条件语句时,我收到断言失败消息。

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?我的问题是:如果我在迭代的条件下使用 nums.end(),它是否获得迭代器的静态值,或者对于每次迭代,它返回一个新的迭代器,该迭代器指向新的re-分配向量? 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. std::vector.erase 使当前迭代器无效,但返回一个迭代器,指向下一个经过擦除的有效迭代器。

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.正如丹尼尔指出的那样,这将使您拥有的任何其他迭代器无效,因此您也必须处理 itslow 情况。

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.当处理更复杂的擦除时,它可以更简单并且更不容易出错,而是处理索引,尽管如果您删除一个元素并且 itslow >= 删除的元素,也存在关于 itslow 的陷阱。 Without seeing what your exact problem is I can't say precisely which to use.没有看到您的确切问题是什么,我无法准确说出使用哪个。

Please see the cppreference for more details regarding erase.有关擦除的更多详细信息,请参阅 cppreference。 There are also several other questions very similar to this.还有其他几个与此非常相似的问题。

https://en.cppreference.com/w/cpp/container/vector/erase std::vector iterator invalidation https://en.cppreference.com/w/cpp/container/vector/erase std::vector 迭代器失效

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

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