STL仿函数functor

it2022-05-05  147

一:仿函数functor介绍

尽管函数指针被广泛用于实现函数回调,但C++还提供了一个重要的实现回调函数的方法,那就是函数对象。 functor,翻译成函数对象,伪函数,算符,是重载了“()”操作符的普通类对象。从语法上讲,它与普通函数行为类似。 实际上仿函数对象仅仅占用1字节,因为内部没有数据成员,仅仅是一个重载的方法而已。实际上可以通过传递函数指针实现类似的功能,但是为了和STL内部配合使用,他提供了仿函数的特性。 之前使用的greater<>与less<>就是仿函数对象。

二:自定义仿函数

struct MyPlus{ int operator()(const int &a , const int &b) const{ return a + b; } }; int main() { MyPlus a; cout << MyPlus()(1,2) << endl;    //1、通过产生临时对象调用重载运算符 cout << a.operator()(1,2) << endl; //2、通过对象显示调用重载运算符 cout << a(1,2) << endl;       //3、通过对象类似函数调用 隐示地调用重载运算符 return 0; }

三:greater简易实现

struct greater { bool operator() (const int& iLeft, const int& iRight) { return (iLeft > iRight);//如果是实现less<int>的话,这边是写return (iLeft<iRight); } }; int main() { int a,b; a = 13, b = 24; if (greater()(a, b)) cout << "a>b"; else cout << "a<b"; system("pause"); return 0; }

四:02--STL算法(函数对象和谓词)《后续》

转载于:https://www.cnblogs.com/ssyfj/p/10791320.html


最新回复(0)