【问题标题】:std::remove_if using other class methodstd::remove_if 使用其他类方法
【发布时间】:2013-05-07 06:44:54
【问题描述】:

我想将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

谢谢!

【问题讨论】:

  • 您的编译器是否实现了 TR1?如果是这样,您仍然可以使用std::tr1::bind,这正是您需要的。
  • 为什么它不是static 成员函数(或根本不是成员函数)?也就是说,您是否应该使用特定的 A 对象来调用 invalidB
  • 你能把InvalidD设为静态吗?
  • @sftrabbit 我需要来自A 特定实例的信息,以确定B 是否有效。它不能是静态的。
  • 哦,我才发现someMethodA 的成员。

标签: c++ methods stdvector predicate remove-if


【解决方案1】:

一旦你进入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

【讨论】:

  • 谢谢,但我有点希望避免声明额外的函数/对象...
  • @Shai 您可以使用mem_funbind1st 来实现,但我想您会发现定义附加对象类型更简单。 (当然,访问 std::bind 或 lambdas 会改变这种情况。)
【解决方案2】:

如果您不想创建额外的仿函数并且您受限于 C++03,请使用 std::mem_fun_refstd::bind1st

std::remove_if(vectorB.begin(), vectorB.end(),
               std::bind1st(std::mem_fun_ref(&A::invalidB), some_A));

或者,如果您的编译器支持 TR1,您可以使用std::tr1::bind

using std::tr1::placeholders::_1;
std::remove_if(vectorB.begin(), vectorB.end(),
               std::tr1::bind(&A::invalidB, some_A, _1));

【讨论】:

  • 我得到以下编译错误:无效重新声明成员函数“std::binder1st<_fn2>::operator()(const std::unary_function<:second_argument_type _fn2::result_type> ::argument_type &) const [with _Fn2=std::const_mem_fun1_ref_t]"
  • PS - 谢谢你的回答。仍然没有工作,但我正在玩它。
  • @Shai:这是标准库中的一个已知缺陷,具有讽刺意味的是,它是由修复不同的缺陷引起的。这就是std::[tr1::]bind 诞生的原因,真的。
猜你喜欢
  • 2014-10-18
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多