std::remove_if 使用其他类方法

2023-07-01C/C++开发问题
3

本文介绍了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_ifB 而不是 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 使用其他类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6