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

发布于 2024-11-10 11:18:55 字数 416 浏览 1 评论 0原文

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

    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
}

我无法弄清楚我做错了什么......有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枯寂 2024-11-17 11:18:55

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

当您使用erase时,它会删除迭代器指向的元素,并返回一个指向下一个元素的迭代器。

如果您希望迭代列表的所有元素,则意味着每当使用 erase 时,您不应该进一步增加它。

这是您应该获得的正常代码:

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

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

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

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

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; 
}

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).

谢绝鈎搭 2024-11-17 11:18:55

您需要将 ++i 放入 else 子句中。 erase 函数返回下一个有效的迭代器,然后您对其进行增量,确保不会迭代每个元素。仅当您选择不擦除时才应该增加它。

You need to put ++i in an else clause. The erase function returns the next valid iterator- and you are then incrementing over it, ensuring that you do not iterate over every element. You should only increment it in the case in which you chose not to erase.

小情绪 2024-11-17 11:18:55

你想要:

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

You want:

if(Player->BoundingBox.Intersect(&(*i)->BoundingBox))
{
    i = Drop_System.erase(i);
}
else {
    ++i; 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文