我是C++的新手,所以我很难找出如何最好地从矢量中移除对象,同时仍然遍历它。在迭代时从矢量中移除一个对象
基本上,我需要遍历两个向量。对于每个项目,如果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
}
}
}
迭代器的工作是有点混乱,我知道我可以使用.erase()
功能上我的载体,但我真的不能传递pit
或bit
。任何帮助赞赏。谢谢
'VECTOR'可能不是我们的最佳容器,因为从载体移除元素是昂贵的,有点尴尬。 – melpomene
相关:http://stackoverflow.com/questions/6096279/keeping-a-valid-vectoriterator-after-erase –
另一个问题是你的方法是'O(n * n)'的复杂性。 100人,100袋,该循环进行10,000次迭代。是否有可能先排序id上的两个向量? – PaulMcKenzie