C++ 标准程序库 笔记 Function Adapters

1. 针对函数对象的配接器,把一个函数对象转化成另外一个函数对象;比如:bind1st 和 bin2nd 把一个需要两个参数的函数对象转化成只要一个参数的函数对象;这种配接方式,只需要在operetor()中重新调用需要被被转化的函数对象即可实现;

例子:

pos = find_if (col1.begin(), col1.end(),

not1(bind2nd(moduus<int>(,2)) );

2. 把成员函数转化为函数对象:mem_fun_ref, mem_fun

在使用上面的函数配接器之前,需要把一个函数转化为函数对象,对于成员函数,完成这个转化工作的是 mem_fun_ref,注意成员函数隐藏了一个参数,因为它需要一个对象来调用,所以mem_fun_ref需要把这个参数也考虑进参数列表中;mem_fun_ref 只能处理无参或单参的成员函数;mem_fun_ref 调用的成员函数还必须是 const函数;

例子:

class Person {

...

public:

void func1(string s){...}

}

vector<Person> col1;

for_each ( col1.begin(), col1.end(),

bind2nd( mem_fun_ref(&Person::func1), "hello"); //mem_fun_ref 默认第一个参数是类对象

如果col1是 Person* 的容器,而不是Person,那么需要用 mem_fun;

vector<Person*> col2; 

for_each ( col2.begin(), col2.end(),

bind2nd( mem_fun(&Person::func1) ) );


3. 把一般函数(非成员函数)转化为函数对象:  ptr_fun

4. 让自定义函数对象也可以使用函数配接器

需要继承std::unary_function或者std::binary_function,他们 typedef 了参数和返回值类型;

例子:

5. 函数对象组合

例子:

// 一元 x

compose_f_gx(bind2nd(multiplies<int>(),5),  
                bind2nd (plus<int>(),10))

compose_f_gx_hx(logical_and<bool>(),  
                bind2nd(greater<int>(),4),  
                bind2nd(less<int>(),7))

// 二元 x, y

pos = search (s .begin(), s. end(),         //string to search in  
                     sub.begin() ,sub.end() ,      //substring to search  
                     compose_f _gx_hy(equal_to<int>(), //compar.  criterion  
                                      ptr_fun(toupper),  
                                      ptr_fun(toupper))); // x 来源于s,y 来源于sub



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值