C++:列表迭代器不可递增

2022-01-10 00:00:00 list iterator increment c++

尝试擦除列表的最后一个元素时出现此错误.我调试了代码并且能够找出导致它的原因和位置,这是我的代码:

Getting this error while trying to erase the last element of a list. I debugged the code and was able to figure out what causes it and where, here's my code:

    for(Drop_List_t::iterator i = Drop_System.begin(); i != Drop_System.end() && !Drop_System_Disable; /**/)
{
    if(Player->BoundingBox.Intersect(&(*i)->BoundingBox))
    {
        i = Drop_System.erase(i);
    }

    ++i; //List iterator crashes here if last entry was deleted
}

我不知道我做错了什么...有什么建议吗?

I can't figure out what I'm doing wrong... Any suggestions?

推荐答案

您的算法有缺陷,因为您不了解 erase 返回的内容.

Your algorithm is flawed because you did not understood what erase returned.

当你使用erase时,它会移除迭代器指向的元素,并返回一个指向下一个元素的迭代器.

When you use erase, it removes the element pointing to by the iterator, and returns an iterator to the next element.

如果您希望遍历列表的所有元素,这意味着无论何时使用 erase 都不应进一步增加它.

If you wish to iterate over all elements of a list, it means that whenever erase was used you should not further increment it.

这是你应该得到的正常代码:

This is the normal code you should have gotten:

if (Player->BoundingBox.Intersect(i->BoundingBox)) {
  i = Drop_System.erase(i);
}
else {
  ++i; 
}

这巧妙地解决了您遇到的问题!因为当你 erase 最后一个元素时,erase 将返回与 end 相同的迭代器,即指向最后一个元素的迭代器元素.此迭代器应永远不会增加(如果列表不为空,它可能会减少).

And this neatly solves the issue you are encountering! Because when you erase the last element, erase will return the same iterator as end, that is an iterator pointing one-past-the-last element. This iterator shall never be incremented (it may be decremented if the list is not empty).

相关文章