19.7 函数对象回顾、系统函数对象与范例

一:函数对象(function object) / 仿函数(functors)回顾

函数对象在stl中,一般都是和算法配合来使用,从而实现一些特定的功能;也就是说,这些函数对象主要用来服务于算法;
函数名(参数列表)
高级话题与新标准第一节、第七节和第八节

#include <map>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>

using namespace std;

class A
{
public:
	bool operator()(int i, int j)
	{
		return i > j;
	}
};

void func()
{
	vector<int> myvector = { 50, 15, 80, 30, 46 };
	A mya;
	sort(myvector.begin(), myvector.end(), mya);

	for (auto iter = myvector.begin(); iter != myvector.end(); ++iter)
	{
		cout << *iter << endl;
	}
}

int main()
{
	cout << "begin" << endl;
	func();
	cout << "end" << endl;
	return 0;
}

二:标准库中定义的函数对象

标准库中提供了很多可以现成拿来使用的函数对象,使用它们之前;
要包含一个头文件 #include <functional>

函数对象分类:
<1>算术运算类:6
<2>关系运算类:6
<3>逻辑运算类:3
<4>位运算类:3

void func()
{
	plus<int>();  //加圆括号是生成一个临时对象,就是个可调用对象
	plus<int> myplus;
}

三:标准库中定义的函数对象范例

#include <map>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <unordered_set>

using namespace std;

void func()
{
	vector<int> myvector = { 50, 15, 80, 30, 46 };
	//sort(myvector.begin(), myvector.end(), greater<int>());  //greater<int>()产生临时对象
	sort(myvector.begin(), myvector.end(), less<int>());
	
	for (auto iter = myvector.begin(); iter != myvector.end(); ++iter)
	{
		cout << *iter << endl;
	}
}

int main()
{
	cout << "begin" << endl;
	func();
	cout << "end" << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值