Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic C++ for remove_if

Tags:

c++

c++11

I have this class

class Point2D
{
public:
 bool isValid();
 // ...
private:
 double x_, y_;
};

I have a std::vector< Point2D > and I would like to remove the invalid points, now I do like this:

bool invalid ( const Point2D& p )
{
 return !p.isValid();
}

void f()
{
 std::vector< Point2D > points;
 // fill points
 points.erase( std::remove_if( points.begin(), points.end(), invalid ), points.end() );
 // use valid points
}

Is there a standard way of doing this (beautifully), for example without the need of "duplicating" the functionality of the class method Point2D::isValid?

Maybe using C++11 lambda (I am not very familiar with lambda)?

like image 898
Alessandro Jacopson Avatar asked Jun 07 '11 09:06

Alessandro Jacopson


2 Answers

Try this:

points.erase(std::remove_if(points.begin(), 
                            points.end(),
                            std::not1(std::mem_fun_ref(&Point2D::isValid))), 
             points.end());
like image 172
n. 1.8e9-where's-my-share m. Avatar answered Oct 25 '22 11:10

n. 1.8e9-where's-my-share m.


Not totally standard but nearly : you can use boost::bind and do the following

points.erase( std::remove_if( points.begin(), points.end(),
  !boost::bind(&Point2D::isValid, _1 )), points.end() );

By the way you should declare the isValid method const.

like image 36
Randall Flagg Avatar answered Oct 25 '22 10:10

Randall Flagg