c++ - 在遍历 vector 时从 vector 中删除对象

标签 c++

我是 C++ 的新手,所以我无法弄清楚如何最好地从 vector 中删除一个对象,同时仍然迭代它。

基本上,我需要遍历两个 vector 。对于每个项目,如果 ID 匹配,我可以删除它们。

//For every person, check to see if the available bags match:
        for(std::vector<Person>::iterator pit = waitingPeopleVector.begin(); pit != waitingPeopleVector.end(); ++pit) {
            for(std::vector<Bag>::iterator bit = waitingBagsVector.begin(); bit != waitingBagsVector.end(); ++bit) {
                int pId = pit->getId();
                int bId = bit->getId();
                if(pId == bId){
                    //a match occurs, remove the bag and person
                }
            }
        }

使用迭代器有点困惑,我知道我可以在我的 vector 上使用 .erase() 函数,但我不能真正通过 pit。任何帮助表示赞赏。谢谢

最佳答案

来自标准:

The iterator returned from a.erase(q) points to the element immediately following q prior to the element being erased. If no such element exists, a.end() is returned.

我会在类似使用 erase 方法的地方使用它:

std::vector<Person>::iterator pit = waitingPeopleVector.begin();
std::vector<Bag>::iterator bit = waitingBagsVector.begin();

while (pit != waitingPeopleVector.end())
{
    bool didit;

    while (bit != waitingBagsVector.end())
    {
        didit = false;
        if (pit->getId() == bit->getId() && !didit)
        {
            bit = waitingBagsVector.erase(bit);
            pit = waitingPeopleVector.erase(pit);
            didit = true;
        }
        else
        {
            ++bit;
        }
    }

    if (didit)
        continue;
    else
        ++pit;
}

关于c++ - 在遍历 vector 时从 vector 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738339/

相关文章:

c++ - 使用 Rice : How to transmit the pointer of Ruby method (callback) to C++ function? 在 C++ 中构建 Ruby 扩展

c++ - 在 Windows CE 6.0/Windows Mobile/Windows Embedded Compact 下使用 RapidXml 出现奇怪的异常

c++ - 如何验证用户将字符串输入到 std::cin 中?

c++ - SFML 2.2 0x00007FFA622C21F9 (sfml-system-2.dll) 处未处理的异常

c++ - 如何编写 C 或 C++ 程序来充当内存和 CPU 周期填充器?

c++ - 在声明行处查看未声明的错误

C++ : getting a wierd print out

C++ 概念与 static_assert

c++ - 如何防止派生类公开私有(private)/ protected 虚函数?

c++ - ifstream.eof() 在 C++ 中未评估为真