开发者

C++ : List iterator not incrementable

开发者 https://www.devze.com 2023-03-09 05:26 出处:网络
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:

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开发者_如何学JAVA't figure out what I'm doing wrong... Any suggestions?


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


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.


You want:

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

精彩评论

暂无评论...
验证码 换一张
取 消