C++ :列表迭代器不可递增
尝试删除列表的最后一个元素时出现此错误。我调试了代码,并能够找出导致它的原因和位置,这是我的代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的算法有缺陷,因为您不理解
erase
返回的内容。当您使用
erase
时,它会删除迭代器指向的元素,并返回一个指向下一个元素的迭代器。如果您希望迭代列表的所有元素,则意味着每当使用
erase
时,您不应该进一步增加它。这是您应该获得的正常代码:
这巧妙地解决了您遇到的问题!因为当你
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:
And this neatly solves the issue you are encountering! Because when you
erase
the last element,erase
will return the same iterator asend
, 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).您需要将
++i
放入else
子句中。erase
函数返回下一个有效的迭代器,然后您对其进行增量,确保不会迭代每个元素。仅当您选择不擦除时才应该增加它。You need to put
++i
in anelse
clause. Theerase
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.你想要:
You want: