函数对象
重载函数调用操作符的类,其对象叫做函数对象,函数对象使用重载的()时,行为类似函数调用,也叫仿函数。
特点:
- 可以有参数,可以有返回值
- 函数对象可以有自己的状态
- 函数对象可以作为参数进行传递
class MyPrint{
public:
MyPrint(){
this->count = 0;
}
void operator()(string test){ //重载调用运算符
cout<<test<<endl;
this->count++;
}
int count; //内部自己状态
};
void test(){
MyPrint myPrint;
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
cout<<"调用次数:"<<myPrint.count<<endl;
}
谓词
返回bool类型的仿函数叫做谓词,接受一个参数叫一元谓词,接受两个参数叫二元谓词。
//一元谓词
class GreaterFive{
public:
bool operator()(int val){
return val>5;
}
}
void test(){
vector<int> v;
for(int i=0;i<10;i++){
v.push_back(i);
}
//查找容器中是否有大于5的数字
vector<int>::iterator it = find_if(v.begin(),v.end(),GreaterFive());
if(it==v.end()){
cout<<"没有找到"<<endl;
}
else{
cout<<"找到了,这个数为"<<*it<<endl;
}
}
STL内建仿函数
引入头文件 #include <functional>
算术仿函数
template<class T> T plus<T> //加
template<class T> T minus<T> //减
template<class T> T multiplies<T> //乘
template<class T> T divides<T> //除
template<class T> T modulus<T> //取模
template<class T> T negate<T> 取反
//一元仿函数 取反
void test(){
negate<int>n;
cout<<n(50)<<endl;
}
//二元仿函数 加法
void test(){
plus<int>n;
cout<<n(50,20)<<endl;
}
关系仿函数
template<class T> T bool equal_to<T>
template<class T> T bool not_equal_to<T>
template<class T> T bool greater<T>
template<class T> T bool greater_equal<T>
template<class T> T bool less<T>
template<class T> T bool less_equal<T>
逻辑仿函数
template<class T> T bool logical_and<T>
template<class T> T bool logical_or<T>
template<class T> T bool logical_not<T>