C ++:List iterator不可增量 [英] C++ : List iterator not incrementable

查看:176
本文介绍了C ++:List iterator不可增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试擦除列表的最后一个元素时出现此错误。我调试代码,并能够找出是什么原因,它在哪里,这里是我的代码:

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
}

推荐答案

你的算法有缺陷,因为你不明白什么<$

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.

如果你想迭代列表的所有元素,这意味着每当<$ c

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

这是您应该拥有的正常代码getten:

This is the normal code you should have gotten:

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

这整齐地解决了你遇到的问题!因为当你擦除最后一个元素时, erase 将返回与 code>,这是一个迭代器指向一个过去的元素。此迭代器不会递增(如果列表不为空,则可以递减)

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 ++:List iterator不可增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆