Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::remove_if usage in C++98

Tags:

c++

vector

c++98

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?

like image 489
Roman Rdgz Avatar asked May 01 '26 22:05

Roman Rdgz


1 Answers

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

like image 60
Jarod42 Avatar answered May 03 '26 11:05

Jarod42