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