我有一个 std::vector<Shape*>
称为场景,它存储指向形状的指针。我需要能够遍历 vector ,将迭代器指向的形状与迭代器中的下一个形状进行比较。如果返回s1->intersects(*s2)
是真的,我需要从 vector 中删除 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);
}
}
}
最佳答案
鉴于您的代码已经假设 vector 中没有空指针,您可以使用空指针作为删除标记,通过将标记与删除分开来大大简化逻辑。
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
.因为如果你最终删除最后两个元素,你将有一个等于 scene.end()
的迭代器。 , 满足条件 it != scene.end() - 1
, 循环将尝试递增它。
关于C++ vector 迭代器 : Compare and Erase Two Elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20302145/