C++ : List iterator not incrementable(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++:列表迭代器不可递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:列表迭代器不可递增
基础教程推荐
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
