问题描述
我想将 std::remove_if
与作为差异类成员函数的谓词一起使用.
I want to use std::remove_if
with a predicate that is a member function of a differenct 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 )
}
有没有办法做到这一点?
Is there a way to do this?
我已经研究了解决方案用于 remove_if 的惯用 C++,但它处理的情况略有不同,即remove_if
是 B
而不是 A
的成员.
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 B
and not A
.
此外,
我无权使用 BOOST 或 c++11
Moreover,
I do not have access to BOOST or c++11
谢谢!
推荐答案
一旦你在 remove_if
中,你就失去了 this
指针A
.所以你必须声明一个功能对象,它包含它,例如:
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 );
}
}
只需将它的一个实例传递给 remove_if
.
Just pass an instance of this to remove_if
.
这篇关于std::remove_if 使用其他类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!