I’m basically looping through all the entries to check whether some entries is to be erased, but seems in a wrong way:
std::vector<HANDLE> myvector;
for(unsigned int i = 0; i < myvector.size(); i++)
{
if(...)
myvector.erase(myvector.begin()+i);
}
Anyone spot the problem in it? How to do it correctly?
Your problem is algorithmic. What happens if two adjacent elements meet your criterion for deletion? The first will be deleted, but because
iis incremented after each iteration of the loop, the second will be skipped. This is because a vector is contiguous in memory, and all elements after the deleted one are moved forwards one index.An ugly hack would be to do the following:
I’m not sure if using iterators would work, because calling
eraseinvalidates iterators to elements after the erased element.The elegant solution would be to use std::remove_if, as GMan suggested. This would abstract away two things:
Edit: I should also add, the hacked solution is O(n2) in the worst case. GMan’s solution is O(n), assuming your removal condition is O(1). I would strongly encourage you to learn and use GMan’s solution.