STL函数对象之预定义函数对象和函数对象绑定器

STL 为我们定义了一些常用的函数对象,如下表。

函数绑定器是函数对象,它能结合函数对象、于特定值或函数在一起使用。它们也是被定义在
<functional>.  看下面的例子:
find_if (coll.begin(),coll.end(), bind2nd (greater<int>(),42))
这个例子 bind2nd greater<int>() 42 结合起来用来检查大于 42 的值。
下面是 STL 为我们定义的函数绑定器:



为成员函数制定的函数对象:
为了在泛型算法中调用一个类的成员函数, STL 为我们提供了这两个绑定器 :



看这样一个例子:
#include <iostream>
#include <vector>
class Person {
private:
std::string name;
public:
void print() const {std::cout << name << std::endl;}
void printWithPrefix (std::string prefix) const {std::cout << prefix << name << std::endl;}
Person(std::string str):name(str){}
};

void foo (const std::vector<Person>& coll){
using std::for_each;
using std::bind2nd;
using std::mem_fun_ref;
// 为每个元素调用 print() 函数。
for_each (coll.begin(), coll.end(),mem_fun_ref(&Person::print));

// 为每个元素调用 printWithPrefix() 函数, ”person”, 是要传递的值。
for_each (coll.begin(), coll.end(),bind2nd (mem_fun_ref (&Person::printWithPrefix),"person: "));

主函数:
vector<Person> vec;
Person per1("panjie");
Person per2("xiaofang");
Person per3("xiaoxiao");
vec.push_back (per1);
vec.push_back (per2);
vec.push_back (per3);
foo(vec);

为普通函数准备的绑定器:
看这样一个例子:
bool check(int elem);
bool strcmp(param1,param2);
pos = find_if (coll.begin(), coll.end(), //rangenot1(ptr_fun(check)));
pos = find_if (coll.begin(), coll.end(), //range
bind2nd(ptr_fun(strcmp),""));

函数的绑定器用起来都很简单的,我们可以想想怎么实现它。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值