Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c++ - std::remove_if using other class method

I want to use std::remove_if with a predicate that is a member function of a differenct calss.

That is

class B;

class A {
    bool invalidB( const B& b ) const; // use members of class A to verify that B is invalid
    void someMethod() ;
};

Now, implementing A::someMethod, I have

void A::someMethod() {
    std::vector< B > vectorB; 
    // filling it with elements

    // I want to remove_if from vectorB based on predicate A::invalidB
    std::remove_if( vectorB.begin(), vectorB.end(), invalidB )
}

Is there a way to do this?

I have already looked into the solution of Idiomatic C++ for remove_if, but it deals with a slightly different case where the unary predicate of remove_if is a member of Band not A.

Moreover,
I do not have access to BOOST or c++11

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Once you're in remove_if, you've lost the this pointer of A. So you'll have to declare a functional object which holds it, something like:

class IsInvalidB
{
    A const* myOwner;
public:
    IsInvalidB( A const& owner ) : myOwner( owner ) {}
    bool operator()( B const& obj )
    {
        return myOwner->invalidB( obj );
    }
}

Just pass an instance of this to remove_if.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...