重载函数调用操作符的类,其对象称为函数对象,由于使用重载运算符()时类似于函数调用,也叫仿函数,函数对象是一个类,不是一个函数。
函数对象的使用
可以像普通函数一样,可以有参数和返回值,超出普通函数概念,可以有自己的状态,函数对象可以作为参数传递。
class MyAdd
{
public:
MyAdd(){this->count=0;}
int operator()(int v1,int v2)
{
return v1+v2;
this->count++;
}
int count;//记录函数调用次数
};
MyAdd m1;
m1(1,2);
count<<"调用次数:"<<m1.count<<endl;
//对象作为参数传递
doAdd(MyAdd &m,int v1,int v2)
{
m(v1,v2);
count<<"调用次数:"<<m.count<<endl;
}
谓词
返回值为bool类型的仿函数叫做谓词
一元谓词:()里面只有一个参数
二元谓词:()里面有两个参数
一元谓词使用
//使用find_if寻找vector中大于5的数
class GreaterFive
{
public:
bool operator()(int val){
return val>5;
}
};
vector<int> v;
for(int i=0;i<10;i++){
v.push_back(i);
}
//对于find_if传入的仿函数,从其实迭代器,一直递增到结束迭代器,每次都调用仿函数
//向仿函数传递的参数就是迭代器指向的容器里的值
//当仿函数返回结果为真的时候,结束循环
//然后返回对应位置的迭代器,返回结果一直假,则最终返回结束迭代器
vector<int>::iterator it=find_if(v.begin(),v,end(),GreaterFive());
if(it!=v.end())
{
cout<<"找到了:"<<*it<<endl;
}else{cout<<"没找到"<<endl;}
二元谓词修改算法排序规则
class Compare
{
public:
bool operator()(int val1,int val2){
return val>val2;//排序从大到小
}
};
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(5);
sort(v.begin(),v.end(),Compare());
内建函数对象
STL提供的一些函数对象,算数仿函数、关系仿函数、逻辑仿函数
使用时包含头文件 #include < functional >
算数仿函数
函数原型:
template<class T> plus<T> //加法仿函数
template<class T> minus<T> //减法仿函数
template<class T> multiplies<T> //乘法仿函数
template<class T> divides<T> //除法仿函数
template<class T> modulus<T> //取模仿函数
template<class T> negate<T> //取反仿函数
使用:
negate<int> n;
n(50);//这里就是对50取反了
plus<int> p;
p(1,2);//这里就是1+2了
关系仿函数
函数原型:
template<class T> bool equal_to<T> //=
template<class T> bool not_equal_to<T> //!=
template<class T> bool greater<T> //>
template<class T> bool greater_equal<T> //>=
template<class T> bool less<T> //<
template<class T> bool less_equal<T> //<=
使用:对于二元谓词修改排序规则,可以直接使用greater仿函数,和我们写的compare仿函数实现是一样的,sort默认使用的是less仿函数
sort(v.begin(),v.end(),greater<int>());
逻辑仿函数
函数原型:
template<class T> bool logical_and<T> //逻辑与
template<class T> bool logical_or<T> //逻辑或
template<class T> bool logical_not<T> //逻辑非
使用:
//容器1元素取反放到容器2
transform(v.begin(),v.end(),v2.begin(),logical_not<bool>());
总结:所有仿函数使用的时候都是创建对象,然后用对象加上小括号调用,在算法里把仿函数当作参数进行传递时,其实就是创建所需要的仿函数对象传进去,算法对象加()来完成仿函数内部的操作,使用谓词时,一般都是使用仿函数对象调用后的返回值来进行判断