C++ vector 迭代器 : Compare and Erase Two Elements

标签 c++ vector iterator erase

我有一个 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/

相关文章:

c++ - 为什么在 C++20 中不推荐使用 std::is_pod?

c# - 使用 C++ std::ofstream 时,FileSystemWatcher 不会触发

c++ - 如何以链式方式在两个容器上构建迭代器

java - 使用单元测试创​​建自定义迭代器

c++ - 为什么我得到 "You must feed a value for placeholder tensor ' 输出 ' 与 dtype int64"?

c++ - 为什么在针对类的const成员函数的range-for循环编译中使用此const自动变量?

c++ - 抽象类和唯一指针 C++ 错误?

c++ - C++类中的多维动态数组

c++ - 从 DLL 访问 vector

C++,插入 List<Class*>,vector<Class> 迭代器