函数对象

来源:互联网 发布:提前上班被开除 知乎 编辑:程序博客网 时间:2024/06/11 21:56
1.函数对象:

重载函数调用操作符的类,其对象常称为函数对象(function object),即它们是行为类似函数的对象。一个类对象,表现出一个函数的特征,就是通过“对象名+(参数列表)”的方式

使用一个类对象,如果没有上下文,完全可以把它看作一个函数对待。

这是通过重载类的operator()来实现的。

“在标准库中,函数对象被广泛地使用以获得弹性”,标准库中的很多算法都可以使用函数对象或者函数来作为自定的回调行为;

2.谓词:

一元函数对象:函数参数1个;

二元函数对象:函数参数2个;

一元谓词 函数参数1个,函数返回值是bool类型,可以作为一个判断式

谓词可以使一个仿函数,也可以是一个回调函数。

二元谓词 函数参数2个,函数返回值是bool类型

3.函数对象的使用(函数对象做函数参数和返回值)

#include <iostream>#include<string>#include <vector>#include <list>#include <set>#include <map>#include <algorithm>#include <functional>using namespace std;//函数对象(重载了函数调用运算符的类对象)template<typename T>class ShowElement{public:ShowElement(){n = 0;}//重载函数调用运算符void operator()(T &t){n++;cout<<t<<endl;}void printN(){cout<<"n:"<<n<<endl;}protected:private:int n;//保持运行调用状态};//函数对象定义void display(){int a = 10;ShowElement<int> showElement;showElement(a);//函数对象的()的执行很像一个函数 //仿函数}//函数对象和普通函数的区别template<typename T>void FuncShowElement(T &t){cout<<t<<endl;}void FuncShowElement2(int &t){cout<<t<<endl;}void display2(){int a = 20;ShowElement<int> showElement;showElement(a);//函数对象的()的执行很像一个函数 //仿函数FuncShowElement<int>(a);//函数模板FuncShowElement2(a);//普通函数}//函数对象 属于类对象 突破函数的概念 保持调用状态信息//函数对象的好处void display3(){vector<int> v;v.push_back(1);v.push_back(3);v.push_back(5);//for_each(v.begin(),v.end(),ShowElement<int>());//匿名函数对象 匿名仿函数//cout<<"--------------------"<<endl;//for_each(v.begin(),v.end(),FuncShowElement2);//回调函数 ShowElement<int> show1;/*template<class _InIt,class _Fn1> inline_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func){// perform function for each element_DEBUG_RANGE(_First, _Last);_DEBUG_POINTER(_Func);return (_For_each(_Unchecked(_First), _Unchecked(_Last), _Func));}*///函数对象作函数参数 for_each算法 函数对象的传递 是元素 值传递 不是引用传递//通过for_each算法的返回值(函数对象做返回值) 看调用的次数show1 = for_each(v.begin(),v.end(),show1);show1.printN();}int main(){display3();system("pause");return 0;}


0 0
原创粉丝点击