请考虑以下事项:
class A
{
public:
bool is_odd(int i)
{
return (i % 2) != 0;
}
void fun()
{
std::vector<int> v2;
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
// fails here
v2.erase(std::remove_if(v2.begin(), v2.end(), std::not1(std::ptr_fun(is_odd))), v2.end());
}
};
上述代码无法否定is_odd()
的影响,因为它是一个成员函数。对std::ptr_fun()
的调用失败。
如何让它发挥作用?请注意,我希望is_odd()
成为非静态成员函数。
答案 0 :(得分:8)
将A::is_odd(int)
用作一元谓词存在多个问题,尤其是当它需要与std::not1()
一起使用时:
A::is_odd(int)
的调用需要两个参数:隐式对象(&#34; this
&#34;)和可见的int
参数。argument_type
和result_type
的函数对象。正确使用此成员函数作为一元谓词需要两个步骤:
std::mem_*fun
函数之一。std::bind1st()
。使用C ++ 11编译器,事情要容易得多,因为std::bind()
会处理这两个问题。假设它是从A
:
... std::not1(std::bind(&A::is_odd, this, std::placeholders::_1)) ...
与C ++ 11之前的编译器相同有点困难。 std::remove_if()
中的用法看起来像这样:
v2.erase(
std::remove_if(v2.begin(),
v2.end(),
std::not1(std::bind1st(std::mem_fun(&A::is_odd), this))),
v2.end());
答案 1 :(得分:1)
只需将is_odd
设为静态,因此不需要隐式this
参数:
static bool is_odd(int i)
无论如何它都不使用任何成员变量或其他成员函数。