1、基本概念
仿函数,顾名思义,仿照函数的使用形式,但本质上是一个类模板。通过重载运算符(),通过类模板生成的模板类就可以像函数一样使用。STL设计仿函数,可以让算法采用不同的策略,从而使算法更加的灵活。
2、相应型别
STL为了统一仿函数,定义了一元函数和二元函数的参数类型及返回值类型,但不支持三元函数。每个定义的仿函数对应进行继承,就可以相同的手法获得仿函数的参数类型和返回值类型。
3、算术类仿函数
这类仿函数,提供基本的算术运算,示例如下:
//算术类仿函数
cout<<plus<int>()(3,5)<<endl;
cout<<minus<int>()(3,5)<<endl;
cout<<multiplies<int>()(3,5)<<endl;
cout<<divides<int>()(3,5)<<endl;
cout<<modulus<int>()(3,5)<<endl;
cout<<negate<int>()(3)<<endl;
4、关系运算类仿函数
这类仿函数,提供基本的比较运算,示例如下:
//关系运算类仿函数
cout<<equal_to<int>()(3,5)<<endl;
cout<<not_equal_to<int>()(3,5)<<endl;
cout<<greater<int>()(3,5)<<endl;
cout<<greater_equal<int>()(3,5)<<endl;
cout<<less<int>()(3,5)<<endl;
cout<<less_equal<int>()(3,5)<<endl;
5、逻辑运算类仿函数
这类仿函数,提供基本的逻辑运算,示例如下:
//逻辑运算类仿函数
cout<<logical_and<int>()(true, false)<<endl;
cout<<logical_or<int>()(true,false)<<endl;
cout<<logical_not<int>()(true)<<endl;
6、参数中转类仿函数
这类仿函数,提供对输入参数不同的输出策略,示例如下:
//证同仿函数
cout<<identity<int>()(3)<<endl;
//选择仿函数
cout<<select1st<pair<int,int>>()(pair<int,int>(3,5))<<endl;
cout<<select2nd<pair<int,int>>()(pair<int,int>(3,5))<<endl;
//投射仿函数
cout<<project1st<int,int>()(3,5)<<endl;
cout<<project2nd<int,int>()(3,5)<<endl;
7、自定义仿函数
使用STL的接口时,除了可以使用STL本身定义的仿函数以为,我们也可以定义自己的仿函数,以实现特定的需求。定义仿函数时,只用定义一个重载运算符()的类模板即可,示例如下:
template<class T>
struct display
{
void operator()(const T& x) const
{
cout<<x<<" ";
}
};
int ia[] = {0,1,2,3,4,5,6,6,6,7,8};
vector<int> iv(ia,ia+sizeof(ia)/sizeof(int));
for_each(iv.begin(),iv.end(),display<int>());