c++中适配器

64 篇文章 0 订阅

功能

  • 扩展函数的参数接口,将自适应二元函数转换为自适应一元函数。

二元适配器

  • ”元“指仿函数中的参数个数。
  • val是for_each提供 tmp
  • 适配器1: bind2nd 或bind1st绑定参数
  • 适配器2:公共继承binary_ function(二元)
  • 适配器3:参数的萃取
  • 适配器4: 对operator( )进行const修饰
class MyPrint:public binary_function<int, intvoid>
{
public :
	void operator() (int val,int tmp) const
	{
		cout< <val+tmp<<" ";
	}
};
for_each(v.begin(),v.end()bind2nd (MyPrint() ,1000)) ;
cout<<endl;

bind2nd 或bind1st绑定

  • bind2nd:将外界数据绑定到MyPrint中的第二个参数tmp。
  • bind1st:将外界数据绑定到MyPrint中的第一个参数val。
cout<<"bind2nd"<<endl;
for_each(v.begin(),v.end()bind2nd(MyPrint()1000) ) ;
cout< <end1 ;

cout<<"bind1st"
for_each(v.begin(),v.end()bind1st(MyPrint()1000) ) ;
cout< <endl ;

一元取反适配器(not1)

  • 找出第一 一个小于3的数
  • 取反适配器1 : not1修饰
  • 取反适配器2: public unary_function(一元)
  • 取反适配器3: 参数萃取
  • 取反适配器4: const修饰operator ()
class MyGreaterThan3:public unary_ function<int,bool>
{
public:
	//一 元谓词
	bool operator()(int val)cqnst
	{
	return val>3;
	}
}
ret = find_ _if(v.begin() ,v.end()not1 (MyGreaterThan3()) ) ;
if(ret != v.end())
{
	cout<<"*ret = "<<*ret<<end;//4
}

二元取反适配器(not2)

  • 取反适配器1 : not2修饰
  • 取反适配器2: public binary_function(二元)
  • 取反适配器3: 参数萃取
  • 取反适配器4: const修饰operator ()
使用not2对内建函数取反
sort(v.begin(), v.endl, not2(greater<int>()));

成员函数适配器

  • 利用mem_fun_ref将类中的成员函数适配。
for_each(v.begin(), v.endl(), mem_fun_ref(&类名称::成员函数));

普通函数适配器

  • 使用ptr_fun转换成函数适配器。
for_each(v.begin(), v.endl(), bind2nd(ptr_fun(函数名),n));

c++11新特性:bind

#include <iostream>
#include <functional>
 
void fn(int n1, int n2, int n3) {
	std::cout << n1 << " " << n2 << " " << n3 << std::endl;
}
 
int fn2() {
	std::cout << "fn2 has called.\n";
	return -1;
}
 
int main()
{
	using namespace std::placeholders;
	auto bind_test1 = std::bind(fn, 1, 2, 3);
	auto bind_test2 = std::bind(fn, _1, _2, _3);
	auto bind_test3 = std::bind(fn, 0, _1, _2);
	auto bind_test4 = std::bind(fn, _2, 0, _1);
 
	bind_test1();//输出1 2 3
	bind_test2(3, 8, 24);//输出3 8 24
	bind_test2(1, 2, 3, 4, 5);//输出1 2 3,4和5会被丢弃
	bind_test3(10, 24);//输出0 10 24
	bind_test3(10, fn2());//输出0 10 -1
	bind_test3(10, 24, fn2());//输出0 10 24,fn2会被调用,但其返回值会被丢弃
	bind_test4(10, 24);//输出24 0 10
	return 0;
}

使用std::bind生成一个可调用对象,这个对象可以直接赋值给std::function对象;在类中有一个std::function的变量,这个std::function由std::bind来赋值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值