STL--适配器

. 适配器

(1)函数适配器:bind2nd绑定,继承binary_function(参1,参2 ,返回值),函数加const常函数;
(2)取反适配器:not1绑定,继承unary_function(参数1,返回值),函数加const;
(3)普通函数指针适配器:ptr_fun将函数指针适配为函数对象,在2nd参数绑定;
(4)成员函数适配器:mem_fun_ref(), 作用域;

代码分析

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
#include<functional>

//-------------------------------------------------------------------------------------------
//函数适配器
class myPrint:public binary_function<int ,int ,void>//一参数,二参数,返回值类型;
{
public:
	void operator()(int val ,int num) const//const不能忘
	{
		cout<<val+num<<endl;
	}
};
void test01()
{
	vector<int>  v;
	for(int i=0;i<10;i++)
	{
		v.push_back(i);
	}
	int num;
	cin>>num;
	for_each(v.begin(),v.end(),bind2nd(myPrint(),num));//多绑定一个参数,继承与const;
}
//-------------------------------------------------------------------------------------------
//一元取反适配器
class Greater:public unary_function<int ,bool>
{
public:
	bool operator()(int val) const
	{
		return val>5;
	}
};
void test02()
{
	vector<int> v;
	for(int i=0;i<10;i++)
	{
		v.push_back(i);
	}

	vector<int>::iterator it = find_if(v.begin(),v.end(),not1(Greater()));//not1,继承,const
	cout<<"小于5的数字为:"<<*it<<endl;
}
//-------------------------------------------------------------------------------------------

//普通函数指针适配器
void  myprint(int val,int start)
{
	cout<<val+start<<endl;
}
void test03()
{
	vector<int> v;
	for(int i=0;i<10;i++)
	{
		v.push_back(i);
	}
	for_each(v.begin(),v.end(),bind2nd(ptr_fun(myprint),10));//ptr_fun先将函数适配为函数对象,在绑定
}

//-------------------------------------------------------------------------------------------
//成员函数适配器
class Person
{
public:
	Person(string name ,int age)
	{
		m_Name=name;
		m_Age = age;
	}
	void showPerson() 
	{
		cout<<"姓名:"<<m_Name<<"年龄;"<<m_Age<<endl;
	}
	string m_Name;
	int m_Age;
};
void test04()
{
	vector<Person> v;
	Person p1("aaa",10);
	Person p2("bbb",20);
	Person p3("ccc",30);
	Person p4("ddd",40);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);

	for_each(v.begin(),v.end(),mem_fun_ref(&Person::showPerson));//mem_fun_ref,作用域
	
}
//-------------------------------------------------------------------------------------------
int main()
{
	test04();
	//test03();
	//test02();
	//test01();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YanWenCheng_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值