std::remove_if using other class method(std::remove_if 使用其他类方法)
问题描述
我想将 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 Band 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 使用其他类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::remove_if 使用其他类方法
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
