std :: remove_if使用其他类方法 [英] std::remove_if using other class method

查看:270
本文介绍了std :: remove_if使用其他类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个谓词作为差异calss的成员函数使用 std :: remove_if



这是

  B类; 

class A {
bool invalidB(const B& b)const; //使用类A的成员来验证B是无效的
void someMethod();
};现在,实现 A :: someMethod ,现在可以使用


$ b <我有

  void A :: someMethod(){
std :: vector< B>载体B;
//用元素填充

//我想从vectorB中基于谓词A :: invalidB
删除___object_object.vector(vectorB.begin(),vectorB。有没有方法可以做到这一点?

p>

我已经研究了
的解决方案 Idiomatic C ++ for remove_if ,但它处理一个稍微不同的情况,其中 remove_if 的一元谓词是 B ,而不是 A



无法访问BOOST或c ++ 11



谢谢!

解决方案

p>一旦你进入 remove_if ,你就失去了
<$ c>的这个 $ c> A
。所以你必须声明一个保存
的功能对象,例如:

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

只需将此实例传递给 remove_if


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!

解决方案

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.

这篇关于std :: remove_if使用其他类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆