19.8 适配器概念、分类、范例与总结

一:适配器基本概念

把一个既有的东西进行适当的改造,比如增加点东西,或者减少点东西,就构成了一个适配器。
三种适配器:容器适配器、算法适配器、迭代适配器。

二:容器适配器

本章第三节学习过双端队列deque
<1>stack:堆栈,是属于阉割版deque
<2>queue:队列,是属于阉割版deque

三:算法适配器(函数适配器)

最典型的就是绑定器(binder)

1、绑定器

老版本为bind1st、bind2nd;c++11中,名字被修改为bind;参考高级话题与新标准第七节。

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;


class A
{
public:
	bool operator()(int i)
	{
		return 40 < i;  //大于40的元素被统计
	}
};

void func()
{
	vector<int> myvector = { 50, 15, 80, 30, 46, 80 };
	//统计某个值出现的次数
	int countInt = count(myvector.begin(), myvector.end(), 80);
	cout << "countInt = " << countInt << endl;

	A myobja;
	countInt = count_if(myvector.begin(), myvector.end(), myobja);
	cout << "countInt = " << countInt << endl;

	//less<int>的operator()的第一个参数绑定为40,这样当调用less<int>()这个可调用对象时;
	//第二个参数,就用这里的placeholders::_1表示,在调用这个函数时,被传入的第一个参数所取代。
	auto bf = bind(less<int>(), 40, placeholders::_1);

	countInt = count_if(myvector.begin(), myvector.end(),
		bind(less<int>(), 40, placeholders::_1));
	cout << "countInt = " << countInt << endl;
}

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

<1>bind:函数适配器中的绑定器;
<2>less():是个函数对象(仿函数),这是个临时对象;
<3>count_if:是个算法。

学习参考网址:
https://en.cppreference.com/w/
https://cplusplus.com/

四:迭代器适配器

1、reverse_iterator

参考第十三章第九节反向迭代器

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

void func()
{
	vector<int> iv = { 100,200,300 };
	for (vector<int>::reverse_iterator riter = iv.rbegin(); riter != iv.rend(); ++riter)
	{
		cout << *riter << 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、付费专栏及课程。

余额充值