gpt4 book ai didi

c++ - std::remove_if 使用其他类方法

转载 作者:太空狗 更新时间:2023-10-29 23:52:17 25 4
gpt4 key购买 nike

我想将 std::remove_if 与作为不同调用的成员函数的谓词一起使用。

也就是

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 的一元谓词是 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 );
}
}

只需将此实例传递给 remove_if

关于c++ - std::remove_if 使用其他类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16518566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com