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

C++ : List iterator not incrementable(C++:列表迭代器不可递增)
本文介绍了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).

这篇关于C++:列表迭代器不可递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)