仿函数(functors)是早期的命名,C++标准中所采用的的新名称是函数对象(function objects)。仿函数在语言层面而言就是个class,以该仿函数产生一个对象,并以此为对象作为算法的一个参数。
就实现而言,仿函数其实就是一个“行为类似函数”的对象,为了能够“行为类似函数”,在其类别定义中必须自定义function call运算符(operator() ),这样就可以在仿函数对象后面加上一对小括号,如下所示
#include<functional>
#include<iostream>
using namespace std;
int main()
{
greater<int> ig;
cout<<boolalpha<<ig(4,6) ;//false
cout<<greater<int>()(6,4);//true
return 0;
}
greater<int> ig产生一个对象ig,ig(4,6)就是调用其operator() ,并传递两个参数4,6.。而greater<int>()就是产生一个临时(无名的)对象,之后通过(4,6)给这个临时对象传递两个参数4,6。这是仿函数主流的用法。
仿函数是STL六大组件之一,主要功能是为了搭配STL算法使用,单独使用仿函数的情况比较少。
STL仿函数的分类,若以操作数的个数划分,可以分为一元和二元仿函数,若以功能划分,可分为算术运算、关系运算、逻辑运算三大类,使用STL内建的仿函数都必须包含<functional>头文件。
//unary_function用来呈现一元函数的参数型别和返回值型别
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
//binary_function用来呈现二元函数的第一参数型别,第二参数型别以及返回值型别
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
算术类仿函数:STL内建的“算术类仿函数”,支持加减乘除,取模(求余数)以及否定(negation)运算。除了否定运算为一元运算,其余都为二元运算。
加法:plus<T> 减法:minus<T> 乘法:multiplies<T> 除法:divides<T> 取模:modulus<T> 否定:negate<T>
//列出继承一元和二元的例子
template<class T>
struct plus:public binary_function<T,T,T>
{
T operator()(const T& x,const T& y) const {return x+y;}
};
template<class T>
struct negate:public unary_function<T,T>
{
T operator()(const T& x) const {return -x;}
};
关系运算类仿函数:STL内建的“关系运算类仿函数”,支持等于、不等于、大于、大于等于、小于、小于等于六种算法。每一个都是二元运算。
等于:equal_to<T> 不等于:not_euqal<T> 大于:greater<T> 大于等于:greater_equal<T> 小于:less<T> 小于等于:less_equal<T>
template<class T>
struct equal_to:public binary_function<T,T,bool>
{
bool operator()(const T& x,const T& y) const {return x==y;}
};
template<class T>
struct greater:public binary_function<T,T,bool>
{
bool operator()(const T& x,const T& y) const {return x > y;}
};
逻辑运算类仿函数:STL内建的“逻辑运算类仿函数”,支持逻辑运算中的And、Or、Not三种算法,其中And和Or是二元运算,Not为一元运算。
逻辑运算And:logical_and<T> 逻辑运算Or:logical_or<T> 逻辑运算Not:logical_not<T>
template<class T>
struct logical_and:public binary_function<T,T,bool>
{
bool operator()(const T& x,const T& y) const {return x&&y;}
};
template<class T>
struct logical_or:public binary_function<T,T,bool>
{
bool operator()(const T& x,const T& y) const {return x || y;}
};
template<class T>
struct logical_not:public unary_function<T,bool>
{
bool operator()(const T& x) const {return !x;}
};