行业知识
从0到1入门C++编程——11 函数对象及算法介绍
2026-11-20 05:59:26
来源:互联网转载
文章目录
- 函数对象
- 1、谓词
- 2、内建函数对象
- (1) 算术仿函数
- (2) 关系仿函数
- (3) 逻辑仿函数
- 常用算法
- 1、常用遍历算法
- (1) for_each
- (2) transform
- 2、常用查找算法
- (1) find和find_if
- (2) find_if
- (3) adjacent_find
- (4) binary_search
- (5) count
- (6) count_if
- 3、常用排序算法
- (1) sort
- (2) random_shuffle
- (3) merge
- (4) reverse
- 4、常用拷贝和替换算法
- (1) copy
- (2) replace
- (3) replace_if
- (4) swap
- 5、常用算术生成算法
- (1) accumulate
- (2) fill
- 6、常用集合算法
- (1) set_intersection 求交集
- (2) set_union 求并集
- (3) set_difference 求差集
函数对象
重载函数调用操作符的类,其对象常称为函数对象。函数对象使用重载的()时,行为类似函数调用,也称仿函数。函数对象的本质是一个类,而不是一个函数。
函数对象的特点:函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值;函数对象超出普通函数的概念,可以有自己的状态;函数对象可以作为参数传递。
函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值,举例如下。
class myAdd{public:int operator()(int a,int b) //有参数,有返回值{return a + b;}};myAdd m;coutpublic:myPrint(){this-count = 0;}void operator()(string s){coutmyPrint m;m("Hello");m("Hello");m("Hello");coutpublic:void operator()(string s){coutm(s);}int main(){myPrint m;fun(m,"Hello");system("pause");return 0;}public:bool operator()(int a) //一元谓词{return a 3;}};void fun(){vectorv.push_back(i+1);}Judge j;vectorcoutfun();system("pause");return 0;}public:bool operator()(int a,int b) //二元谓词{return a b;}};void printVector(vectorfor(vectorcoutvectorfun();system("pause");return 0;}plusfun();system("pause");return 0;}// order [_First, _Last), using operator
上一篇:五常中文域名怎么做