函数适配器

最近学的时候碰到一个东西叫函数适配器。越学C++,越觉得它牛逼啊。

总结一下。

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
/*
函数适配器:
STL中已经定义了大量的函数对象,但是有时候需要对函数返回值进行进一步的简单计算,
或者填上多余的参数,不能直接代入算法,函数适配器实现了这一功能,将一种函数对象
转化为另一种符合要求的函数对象。函数适配器可以分为4大类:绑定适配器,组合适配器,
指针函数适配器和成员函数适配器
*/

/*
绑定器(binder):binder通过把二元函数对象的一个实参绑定到一个特殊的值上,
将其转换成一元函数对象。C++标准库提供两种预定义的binder适配器,bind1st
和bind2nd,前者把值绑定到二元函数对象的第一个实参上,后者绑定到第二个实参上。
取反器(negator):negator是一个将函数对象的值翻转的函数适配器。标准库提供两个
预定义的negator适配器,not1翻转一元预定义函数对象的真值,而not2翻转二元谓词函数的真值
*/
struct IsGreat
{
	IsGreat(int i)
	{
		n_num = i;
	}
	bool operator()(int &num)
	{
		if (num > n_num)
		{
			return true;
		}
		return false;
	}
private:
	int n_num;
};
void test()
{
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i + 1);
	}
	for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	int num1 = count(v1.begin(), v1.end(), 3);
	cout << "num1: " << num1 << endl;

	//通过谓词求大于2的个数
	int num2 = count_if(v1.begin(), v1.end(), IsGreat(2));
	cout << "num2: " << num2 << endl;

	//通过预定义的函数对象 求大于2 的个数
	//greater<int>() 有两个参数 左参数来自容器的元素 右参数固定成2(通过bind2nd来固定)
	int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 2));
	cout << "num3: " << num3 << endl;

	//求奇数的个数
	int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus<int>(), 2));
	cout << "奇数的个数: " << num4 << endl;

	//求偶数的个数
	int num5 = count_if(v1.begin(), v1.end(), not1(bind2nd(modulus<int>(), 2)));
	cout << "偶数的个数:" << num5 << endl;
}
int main()
{
	test();

	getchar();
	getchar();
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值