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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...