c++ - 遍历 vector 并删除某些元素的正确方法是什么

标签 c++ arrays loops vector iterator

<分区>

我遇到了一个问题,我想遍历我的 vector 并删除不再需要的元素。它失败的原因很明显,但是当我尝试我天真的方法时我没有看到它。基本上,当我删除一个元素时,迭代器会失效,并且循环无法继续。我所做的是:

    #define GOOD 1
    #define BAD 0

    struct Element
    {
        Element(int isGood) : good(isGood){}
        bool good;
    };

    int main()
    {
        std::vector<Element> arr;
        arr.push_back(Element(BAD));
        arr.push_back(Element(GOOD));
        arr.push_back(Element(BAD));
        arr.push_back(Element(GOOD));

    //__CLEAN ARRAY__//
        for (auto it = arr.begin(); it != arr.end(); ++it)
        {
            if ((*it).good == false) arr.erase(it);
        }
    }

所以很明显这行不通,我想知道这样做的正确/最佳方法是什么。如果没有找到合适的,我的下一步是用新的迭代器重新启动循环,但这似乎也是一种浪费。理想情况下,循环会使用新的迭代器从中断处继续?

谢谢。

最佳答案

你想要:

arr.erase( std::remove_if(arr.begin(), arr.end(), [](auto& obj){return obj.good == false;}), arr.end() );

及其所谓的移除-删除成语:

https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

但是如果你想修复循环那么它是可能的,erase 返回下一个有效的迭代器所以你应该使用它:

    for (auto it = arr.begin(); it != arr.end(); )
    {
      if ((*it).good == false) 
        it = arr.erase(it);
      else
        it++;
    }

关于c++ - 遍历 vector 并删除某些元素的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41862426/

相关文章:

c++ - 如何将 char [HEX] 数组转换为整数?

arrays - 如何从node js中的json对象获取值数组

c - 让程序在 C 中重复输入

php - 如何通过针对另一个数组测试数组结果来将复选框设置为选中?

python - 通过网络发送结构化数据

C++ 常见问题解答 32.8 "pass an object of a C++ class to/from a C function"问题

c++ - 尝试减少 C++ 调试编译中的内存分配大小

c++ - 数组和指针

arrays - 创新设置: Single installer that reads names from an INI file and creates an installation for each name

python - Python : Alert if more than N errors in a given period? 日志解析