Sha*_*hai 2 c++ methods predicate stdvector 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() ;
};
Run Code Online (Sandbox Code Playgroud)
现在,实施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 )
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
我已经研究了用于remove_if的Idiomatic C++的解决方案
,但是它处理的是一个稍微不同的情况,其中一元谓词remove_if是成员B而不是成员A.
而且,
我无法访问BOOST或c ++ 11
谢谢!
一旦你进入remove_if,你就失去了this指针
A.所以你必须声明一个包含它的功能对象,例如:
class IsInvalidB
{
A const* myOwner;
public:
IsInvalidB( A const& owner ) : myOwner( owner ) {}
bool operator()( B const& obj )
{
return myOwner->invalidB( obj );
}
}
Run Code Online (Sandbox Code Playgroud)
只需将此实例传递给remove_if.