[英]C++ Vector Iterator: Compare and Erase Two Elements
我有一个名为scene的std::vector<Shape*>
,它存储指向Shapes的指针。 我需要能够遍历向量,将迭代器指向的形状与迭代器中的下一个形状进行比较。 如果s1->intersects(*s2)
的返回为真,我需要从向量中删除s1和s2。 以下代码不正确,我得到一个异常vector interator is not incrementable
。
我怎么解决这个问题?
while (scene.size() > 1)
{
for (std::vector<Shape*>::iterator it = scene.begin(); it != scene.end() - 1; it++)
{
Shape* s1 = (*it);
Shape* s2 = (*(it + 1));
if (s1->intersects(*s2))
{
delete s1;
delete s2;
// Remove the pointers to s1 and s2 from the vector.
it = scene.erase(it);
it = scene.erase(it);
}
}
}
看看代码如何假定向量中没有空指针,您可以使用空指针作为删除标记,通过将标记与擦除分开来大大简化逻辑。
for (std::vector<Shape*>::iterator it = scene.begin(); it < scene.end() - 1; ++it)
{
Shape*& s1 = (*it);
Shape*& s2 = (*(it + 1));
if (s1->intersects(*s2))
{
delete s1;
delete s2;
s1 = NULL;
s2 = NULL;
++it;
}
}
scene.erase(std::remove(scene.begin(), scene.end(), NULL), scene.end());
it != scene.end() - 1
,您的原始代码可能已经通过更改it != scene.end() - 1
来修复it != scene.end() - 1
到it < scene.end() - 1
。 因为如果最终删除最后两个元素,你将拥有一个等于scene.end()
的迭代器,它满足条件it != scene.end() - 1
,并且循环将尝试递增它。
向量迭代器在擦除时变为无效。 你应该使用vector :: erase(iterator first,iterator last); 同时擦除矢量中的多个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.