STL学习之十三:预定义函数和函数适配器

本文主要介绍预定义函数和函数适配器。预定义好的函数对象,能实现不同类型的数据的运算, 实现了数据类型 和算法的分离===》通过函数对象技术实现。下面是示例代码:

#include "iostream"
using namespace std;

#include "vector"
#include "set"
#include "queue"
#include "list"
#include "algorithm"
#include "string"
#include "functional"

// plus<type> 预定义好的函数对象,能实现不同类型的数据的 运算
// 实现了数据类型 和算法的分离===》通过函数对象技术实现的
void main21()
{
	//template<class _Ty>
	//struct plus
	//	: public binary_function<_Ty, _Ty, _Ty>
	//{	// functor for operator+
	//	_Ty operator()(const _Ty& _Left, const _Ty& _Right) const
	//	{	// apply operator+ to operands
	//		return (_Left + _Right);
	//	}
	//};
	plus<int> intAdd;
	int x = 10;
	int y = 20;
	int z = intAdd(x,y);// x+y
	cout << "z:" << z << endl;//结果为 30

	plus<string> stringAdd;
	string s1 = "aaa";
	string s2 = "bbb";
	string s3 = stringAdd(s1,s2);
	cout << "s3:" <<s3 << endl;// 结果为 aaabbb

	vector<string> v1;
	v1.push_back("bbb");
	v1.push_back("aaa");
	v1.push_back("ccc");
	v1.push_back("zzz");

	sort(v1.begin(),v1.end(),greater<string>());// 从大到小
	for (vector<string>::iterator it=v1.begin();it!=v1.end();it++)
	{
		cout << *it << endl;
	}
	// 求 ccc 出现的个数
	string sc = "ccc";
	//equal_to<string>() 有两个参数,来自容器,来自sc
	// bind2nd 函数适配器,把预定义函数对象 和第二个参数进行绑定
	int num = count_if(v1.begin(),v1.end(),bind2nd (equal_to<string>(),sc));
	cout << "num:" << num << endl;

}

class IsGreat
{
public:
	IsGreat(int i)
	{
		m_num = i;
	}
	bool operator()(int &num)
	{
		if (num > m_num)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
protected:

private:
	int m_num;
};
void main22()
{
	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 << "=3 的 num1:"<< num1 << endl;

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

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

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

	// 求偶数的个数
	int num5 = count_if(v1.begin(),v1.end(),not1(bind2nd(modulus<int>(),2)));// 对上面去反
	cout << "偶数的个数num5:" << num5 << endl;
}
void main()
{
	//main21();
	main22();// 函数适配器综合性案例
	cout << "hello..."<< endl;

	system("pause");

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bixiwen_liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值