I'm new to C++ so I'm having trouble figuring out how to best remove an object from a vector while still iterating through it.
Basically, I need to iterate through two vectors. For every item, if the ID's match, I can remove them.
//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
}
}
}
Working with iterators is a bit confusing, I know I can use the .erase() function on my vectors, but I can't really pass pit or bit. Any help appreciated. Thanks
vectormight not be the best container for this, because removing elements from a vector is expensive and a bit awkward.O(n*n)complexity. 100 peope, 100 bags, that loop goes for 10,000 iterations. Is it possible to sort the two vectors on id first?pitorbit? Why can't you? And have you tried the simpler exercise of deleting elements from one container?std::findshould make your job a bit easier. You can also hoistint pId = pit->getId();up one loop.