2

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?

1
  • 1
    you meant outages.begin(), right? Commented Aug 25, 2014 at 14:18

2 Answers 2

7

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).

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I have been bitten more than once by leaving out the second , outages.end()...
4

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());

1 Comment

+1 I have been bitten more than once by leaving out the second , outages.end()...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.