STL函数适配器

函数适配器

1.初识函数适配器
1)使用bind2nd进行绑定
2)需要继承 public binary_function<参数类型1,参数类型2,返回值类型>
3)使用const修饰operator()

class myPrint:public binary_function<int,int,void>
{
public:
	void operator()(int val,int start) const //限定数据
	{
		cout<<"val: "<<val<<"start:"<<start<<"val+start= "<<val+start<<endl;
	}
};

void text01()
{

	vector<int>v;
	for (int i=0;i<10;i++)
	{
		v.push_back(i);
	}
	cout<<"尊贵的用户请输入起始值:"<<endl;
	int num;
	cin>>num;

	for_each(v.begin(),v.end(),bind2nd(myPrint(),num));
}

2.取反函数适配器
1)使用not1进行取反
2)继承public unary_function<int,bool>
3)使用const修饰operator()

class GreaterThenFive:public unary_function<int,bool>
{

public:
	bool operator()(int v)const
	{

		return v>5;
	}
};

void text02()
{
	vector<int>v;
	for (int i=0;i<10;i++)
	{
		v.push_back(i);
	}
	//查找大于5的数字
 //vector<int>::iterator pos=	find_if(v.begin(),v.end(),not1(GreaterThenFive()));
	 vector<int>::iterator pos=	find_if(v.begin(),v.end(),not1 (bind2nd(greater<int>(),5)));
	if (pos!=v.end())
	{
		cout<<"找到小于5的数字为:"<<*pos<<endl;
	}
	else
	{
		cout<<"未找到"<<endl;
	}
}

3.函数指针适配器
1)将函数指针适配为函数对象
2)用ptr_fun将函数指针适配为函数对象

void myPrint3(int v,int start)
{
	cout<<v+start<<" ";
}
void text03()
{
	vector<int>v;
	for (int i=0;i<10;i++)
	{
		v.push_back(i);
	}

	//将函数指针适配为函数对象
	//ptr_fun
	for_each(v.begin(),v.end(),bind2nd(ptr_fun(myPrint3),100));

}

4.成员函数适配器
1)如果容器存放的是对象指针, 那么用mem_fun
2)如果容器中存放的是对象实体,那么用mem_fun_ref

class Person
{
public:
	Person(string name,int age)
	{
		this->name=name;
		this->age=age;
	}
	string name;
	int age;
	void showXinxi()
	{
		cout<<"姓名:"<<name<<"年龄:"<<age<<endl;
	}

};
void text04()
{
	vector<Person>v;
	Person p1("李亦非",20);
	Person p2("冰冰侠",18);
	Person p3("李雅婷",22);
	Person p4("千峰",23);
	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::showXinxi));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值