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 使用其他类方法
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
