函数对象简介
函数对象,也叫仿函数,是一种实现了operator()的类型。STL使用函数对象用在一些算法上。
函数对象比直接的函数调用提供了2方面的优点。
1:函数对象可以包含自身的状态(因为是类类型,所以可以封装自身的状态/属性)。
2:因为函数对象是一种类类型,所以可以用来实例化模版参数。
创建函数对象
为了创建一个函数对象,必须创建一个类,并实现operator()。例如:
/*
**函数对象例子
**函数对象可以拥有自己的状态,Functor::value
*/
class Functor
{
public:
Functor(int _value):value(_value){}
public:
bool operator()(int i1)
{
return i1>value;
}
private:
int value;
};
//函数对象的调用方式就像是调用一个函数
int main()
{
Functor f(60);
cout<<f(100)<<endl;
}
上面的例子简单的展示了如何创建和调用函数对象,函数对象的调用方式就像是调用一个函数,但实际上是调用类的成员函数operator()。
函数对象和容器
函数对象的一种用途就是为容器指定排序算法,例如,STL中的set容器,它存储的类型要求能够进行“<”比较操作。
class Student
{
public:
enum SEX{BOY,GIRL};
public:
Student(int _age,SEX _sex):age(_age),sex(_sex){};
int getAge(){return age;}
private:
SEX sex;
int age;
};
像上面的Student类就无法存储在set里面,因为set不知道如何进行‘<’比较操作。
我们有两种方法解决:
1:为Student类重载operator<
2:使用函数对象指明‘<’比较操作。
这里介绍第二种方法,函数对象定义如下。
class StudentLess
{
public:
bool operator()(Student s1,Student s2)
{
return s1.getAge()<=s2.getAge();
}
};
这样,我们就可以用set存储Student类了。
set<Student,StudentLess> setStu;
函数对象和算法
函数对象的另一个用途就是用在算法中。如下;
class MyRemove
{
public:
bool operator()(int n)
{
return n<=3 && n>=5 ;
}
};
int main()
{
list<int> l;
for(int i=1;i<=10;i++)
l.push_back(i);
l.remove_if(MyRemove());
}
上面的例子把list容器l中3,4,5去掉。
要注意一点的是,list中的remove_if和通用算法中的remove_if是不一样的。
list中的remove_if会直接删掉元素,而通用算法中的remove_if是返回一个要删除的元素的迭代器,从此迭代器到容器结尾都是要删除的元素。
//使用list中的remove_if
l.remove_if(MyRemove());
//使用通用算法中的remove_if,iter为需要删除的第一个元素
list<int>::iterator iter=remove_if(l.begin(),l.end(),MyRemove());
l.erase(iter,l.end());