在C ++中定义谓词函数的正确方法 [英] Correct Way to Define a Predicate Function in C++

查看:266
本文介绍了在C ++中定义谓词函数的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写用于STL算法的谓词函数。我看到他们有两种方法来定义一个谓词:

I'm trying to write predicate function for use with STL algorithms. I see that they are two ways to define a predicate:

(1)使用一个简单的函数如下:

(1) Use a simple function as below:

bool isEven(unsigned int i)   
{ return (i%2 == 0); }

std::find_if(itBegin, itEnd, isEven); 

(2)使用operator()函数如下:

(2) Use the operator() function as below:

class checker {  
public:  
  bool operator()(unsigned int i)  
  { return (i%2 == 0); }  
}; 

std::find_if(itBegin, itEnd, checker); 

我有更多的用于第二个类型,因为我通常想创建一个谓词对象与一些成员并在算法中使用它们。当我在checker中添加相同的isEven函数并将其用作谓词时,会出现错误:

3.语法错误:

I have more use for the second type as I usually would like to create a predicate object with some members in it and use them in the algorithm. When I add the same isEven function inside checker and use it as a predicate, I get an error:
3. Syntax which gives error:

class checker { 
    public: 
       bool isEven(unsigned int i) 
       { return (i%2 == 0); }
}; 

checker c; 
std::find_if(itBegin, itEnd, c.isEven); 

在编译期间调用c.isEven会出现错误,说明未定义的某个函数的引用。有人可以解释为什么3.是给错误?

Calling c.isEven gives an error during compilation saying undefined reference to some function. Can someone explain why 3. is giving error? Also, I would appreciate any pointers to read about predicate and iterator basics.

推荐答案

我猜这是因为<$ c的类型$ c> c.isEven() is,

bool (checker::*)(unsigned int) // member function of class

这可能不是预期的 find_if () std :: find_if 应该期待一个函数指针( bool(*)(unsigned int))或函数对象。

which may not be expected by find_if(). std::find_if should be expecting either a function pointer (bool (*)(unsigned int)) or a function object.

编辑:另一个约束:非 - static 函数指针必须由对象调用。在你的情况下,即使你成功传递成员函数,仍然 find_if()将不会有任何检查器的信息 object;因此,接受成员函数指针参数的 find_if()重载是没有意义的。

Edit: Another constraint: A non-static member function pointer must be called by the class object. In your case, even if you succeed to pass the member function then still find_if() will not have any information about any checker object; so it doesn't make sense to have find_if() overloaded for accepting a member function pointer argument.

strong>注意:一般来说 c.isEven 不是正确的方法传递成员函数指针;它应该作为& checker :: isEven 传递。

Note: In general c.isEven is not the right way to pass member function pointer; it should be passed as, &checker::isEven.

这篇关于在C ++中定义谓词函数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆