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(), //range not1(ptr_fun(check)));
pos = find_if (coll.begin(), coll.end(), //range
bind2nd(ptr_fun(strcmp),""));
函数的绑定器用起来都很简单的,我们可以想想怎么实现它。
函数绑定器是函数对象,它能结合函数对象、于特定值或函数在一起使用。它们也是被定义在
<functional>.
find_if (coll.begin(),coll.end(), bind2nd (greater<int>(),42))
这个例子 bind2nd
下面是 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;
//
for_each (coll.begin(), coll.end(),mem_fun_ref(&Person::print));
//
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(),
pos = find_if (coll.begin(), coll.end(), //range
bind2nd(ptr_fun(strcmp),""));
函数的绑定器用起来都很简单的,我们可以想想怎么实现它。