来看仿函数的通俗定义:仿函数(functor)又称为函数对象(function object)是一个能行使函数功能的类。仿函数的语法几乎和我们普通的函数调用一样,不过作为仿函数的类,都必须重载operator()运算符。
先考虑一个应用防函数的简单例子:假设有一个vector
count_if(first,last,comp) (在comp为true的情况下计数):first为首迭代器,last为末迭代器,comp为比较bool函数,为true则计数,函数返回型是int,count_if要求comp函数只能带一个参数(所以引出了仿函数的概念)。
为使用count_if函数,你的comp函数可能会写成这样:
bool comp(const string& str) {
return str.length()<5;
}
int res=count_if(vec.begin(), vec.end(), comp);
其中count_if函数的第三个参数是一个函数指针,返回一个bool类型的值。一般的,如果需要将特定的阈值长度也传入的话,我们可能将函数写成含有2个参数:
bool comp(const string& str, int len) {
return str.length()
这个函数看起来比前面一个版本更具有一般性,但是他不能满足count_if函数的参数要求。
仿函数其实是上述解决方案中的第四种方案:成员变量。成员函数可以很自然的访问成员变量:
暂时抛开上面的问题,我们来感受一下仿函数的作用,下面我们设计了两个类,来对比仿函数时如何实现传2个参数的:
第一个仿函数实现接收一个参数:
class Func{
public:
void operator() (const string& str) const {
cout<>>helloworld!
第二个仿函数实现接收两个参数:
class Func{
public:
explicit Func(const string& str) : ss(str){}
void operator() (const string& str) const{
cout<>>hellois world
我相信这个例子能让你体会到一点点仿函数的作用了;它既能想普通函数一样传入给定数量的参数,还能存储或者处理更多我们需要的有用信息。
让我们回到count_if的问题中去,是不是觉得问题变得豁然开朗了?
下面将我们实现count_if的整个过程附上:
#include
#include
#include
#include
using namespace std;
class ShorterThan {
public:
explicit ShorterThan(int maxLength) : length(maxLength) {}
bool operator() (const string& str) const
{
return str.length() < length;
}
private:
const int length;
};
int main()
{
vector myVector;
myVector.push_back("Jack");
myVector.push_back("Tom");
myVector.push_back("Mchical");
for (int i=0; i<3; i++){
cout<
这里需要注意的是,不要纠结于语法问题:ShorterThan(length)似乎并没有调用operator()函数?其实它调用了,创建了一个临时对象。你也可以自己加一些输出语句看一看。