其他分享
首页 > 其他分享> > c – 使用其他类方法的std :: remove_if

c – 使用其他类方法的std :: remove_if

作者:互联网

我想使用std :: remove_if和一个谓词,它是一个不同的calss的成员函数.

那是

class B;

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

现在,实现A :: someMethod,我有

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

有没有办法做到这一点?

我已经研究了解决方案
Idiomatic C++ for remove_if,但它处理的情况略有不同,其中remove_if的一元谓词是Band而不是A的成员.

此外,
我无法访问BOOST或c 11

谢谢!

解决方法:

一旦你进入remove_if,你就失去了这个指针
答:所以你必须声明一个持有的功能对象
它,像:

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

只需将此实例传递给remove_if即可.

标签:remove-if,c,methods,stdvector,predicate
来源: https://codeday.me/bug/20191007/1865290.html