Reputation: 13254
I was looking for a smart way of erasing some elements in a vector while iterating, and found this question.
Of course, it won't work for me, since C++98 doesn't have lambdas. Looked for remove_if info and found this at cppreference. So this is how my code looks:
#include <algorithm>
#include <vector>
bool isOutageValid(const Outage& outage){
return outage.getEndTime() >= 0;
}
std::vector<Outage> outages;
// Some stuff to fill the vector
outages.erase(std::remove_if(outages.begin(), outages.end(), isOutageValid));
for(vector<Outage>::iterator o=outages.begin(); o!=outages.end(); o++){
std::cout << o->getStartTime() << " " << o->getEndTime() << std::endl;
}
I am debugging with 4 Outages into a vector, where I know the first is invalid and the rest of them valid. After executing the erase, the vector size is 3, so it looks ok. But if I iterate with the for
loop to inspect the 3 Outages into the vector, the second one has been erased instead of the first.
I even debugged the isOutageValid method, and it is the first the only one who is returning false. Is there any mistake I'm missing?
Upvotes: 2
Views: 850
Reputation: 48447
1.You forgot to specify the second argument of erase
, which is the end of the range which is erased:
outages.erase(std::remove_if(outages.begin, outages.end(), isOutageValid), outages.end());
2.The condition is invalid, you should negate it:
#include <functional>
outages.erase(std::remove_if(outages.begin, outages.end(), std::not1(std::ptr_fun(&isOutageValid))), outages.end());
Upvotes: 4
Reputation: 217235
It should be:
outages.erase(std::remove_if(outages.begin, outages.end(), isNotOutageValid), outages.end());
Currently, you partition outages not valid first, valid last (in other words, your predicate is inverted).
And then remove the fist valid element (instead of a range).
Upvotes: 7