gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:38:21 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com