标签:
回顾
五、STL中内置的函数对象
一、适配器
1、三种类型的适配器:
(1)容器适配器:用来扩展7种基本容器,利用基本容器扩展形成了栈、队列和优先级队列
(2)迭代器适配器:(反向迭代器、插入迭代器、IO流迭代器)
(3)函数适配器:函数适配器能够将仿函数和另一个仿函数(或某个值、或某个一般函数)结合起来。
【1】针对成员函数的函数适配器
【2】针对一般函数的函数适配器
二、函数适配器
1、示例
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
bool is_odd(int n)
{
return n % 2 == 1;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
vector<int> v(a, a + 5);
cout << count_if(v.begin(), v.end(), is_odd) << endl;
//计算奇数元素的个数
// 这里的bind2nd将二元函数对象modulus转换为一元函数对象。
//bind2nd(op, value) (param)相当于op(param, value)
cout << count_if(v.begin(), v.end(),
bind2nd(modulus<int>(), 2)) << endl; //bind2nd函数对象或适配器
cout << count_if(v.begin(), v.end(),
bind1st(modulus<int>(), 2)) << endl; //bind2nd函数对象或适配器
//bind1st(op, value)(param)相当于op(value, param);
cout << count_if(v.begin(), v.end(),
bind1st(less<int>(), 4)) << endl; //>4,函数适配器
cout << count_if(v.begin(), v.end(),
bind2nd(less<int>(), 4)) << endl; //<4,函数适配器
return 0;
}
这里的bind2nd将二元函数对象modulus转换为一元函数对象。是如何做到的呢?跟踪源码就知道了。
首先,bind2nd 是一个模板函数,如下:
// TEMPLATE FUNCTION bind2nd
template < class _Fn2,
class _Ty > inline
binder2nd<_Fn2> bind2nd(const _Fn2 &_Func, const _Ty &_Right)
{
// return a binder2nd functor adapter
typename _Fn2::second_argument_type _Val(_Right);
return (std::binder2nd<_Fn2>(_Func, _Val));
}将匿名对象modulus<int>() 和 2 传递进去,返回值是 std::binder2nd<_Fn2>(_Func, _Val); 即是一个模板类对象,看binder2nd 模板类
// TEMPLATE CLASS binder2nd
template<class _Fn2>
class binder2nd
: public unary_function < typename _Fn2::first_argument_type,
typename _Fn2::result_type >
{
// functor adapter _Func(left, stored)
public:
typedef unary_function < typename _Fn2::first_argument_type,
typename _Fn2::result_type > _Base;
typedef typename _Base::argument_type argument_type;
typedef typename _Base::result_type result_type;
binder2nd(const _Fn2 &_Func,
const typename _Fn2::second_argument_type &_Right)
: op(_Func), value(_Right)
{
// construct from functor and right operand
}
result_type operator()(const argument_type &_Left) const
{
// apply functor to operands
return (op(_Left, value));
}
result_type operator()(argument_type &_Left) const
{
// apply functor to operands
return (op(_Left, value));
}
protected:
_Fn2 op; // the functor to apply
typename _Fn2::second_argument_type value; // the right operand
};即构造时,binder2nd 的2个成员op 和 value 分别用modulus<int>() 和 2 初始化。接着看count_if 中的主要代码:
for (; _First != _Last; ++_First)
if (_Pred(*_First))
++_Count;
*_First 就是遍历得到的容器元素了,当满足_Pred 条件时_Count++,此时可以看成是:std::binder2nd< modulus<int> >(modulus<int>(), 2)(*_First) 也就是调用binder2nd 类的operator() 函数,返回 return (op(_Left, value)); 也就是modulus<int>()(*_First, 2); 也就是调用modulus 类的operator() 函数,如下:
// TEMPLATE STRUCT modulus
template<class _Ty>
struct modulus
: public binary_function<_Ty, _Ty, _Ty>
{
// functor for operator%
_Ty operator()(const _Ty &_Left, const _Ty &_Right) const
{
// apply operator% to operands
return (_Left % _Right);
}
};
与bind2nd 类似的还有 bind1st,顾名思义是绑定第一个参数的意思,如下的表达式:count_if(v.begin(), v.end(), bind1st(less<int>(), 4)) ; 也就是说计算容器中大于4的元素个数。这里绑定的是左操作数。
三、函数适配器应用实例
(一)、针对成员函数的函数适配器
1、示例
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
using namespace std;
class Person
{
public:
Person(const string &name) : name_(name) {}
void Print() const
{
cout << name_ << endl;
}
void PrintWithPrefix(string prefix) const
{
cout << prefix << name_ << endl;
}
private:
string name_;
};
void foo(const vector<Person> &v)
{
for_each(v.begin(), v.end(), mem_fun_ref(&Person::Print)); //mem_fun_ref先将不带参数转换成一元
for_each(v.begin(), v.end(), bind2nd(mem_fun_ref(&Person::PrintWithPrefix), "person: ")); //mem_fun_ref先将一元转换成二元,bind2nd再将二元转换成一元
}
void foo2(const vector<Person *> &v)
{
for_each(v.begin(), v.end(), mem_fun(&Person::Print));
for_each(v.begin(), v.end(), bind2nd(mem_fun(&Person::PrintWithPrefix), "person: "));
}
int main(void)
{
vector<Person> v; //针对对象
v.push_back(Person("tom"));
v.push_back(Person("jerry"));
foo(v);
vector<Person *> v2; //针对指针
v2.push_back(new Person("tom"));
v2.push_back(new Person("jerry"));
foo2(v2);
return 0;
}
在foo 函数中,第一行的mem_fun_ref 将不带参数的成员函数转换为一元函数对象,具体流程大家可以自己跟踪代码,实际上跟上面bind2nd 是类似的,需要稍微说一下的是传递函数指针的情况:
template < class _Result,
class _Ty > inline
const_mem_fun_ref_t<_Result, _Ty>
mem_fun_ref(_Result (_Ty::*_Pm)() const)
{
// return a const_mem_fun_ref_t functor adapter
return (std::const_mem_fun_ref_t<_Result, _Ty>(_Pm));
}
// TEMPLATE CLASS const_mem_fun_ref_t
template < class _Result,
class _Ty >
class const_mem_fun_ref_t
: public unary_function<_Ty, _Result>
{
// functor adapter (*left.*pfunc)(), const *pfunc
public:
explicit const_mem_fun_ref_t(_Result (_Ty::*_Pm)() const)
: _Pmemfun(_Pm)
{
// construct from pointer
}
_Result operator()(const _Ty &_Left) const
{
// call function
return ((_Left.*_Pmemfun)());
}
private:
_Result (_Ty::*_Pmemfun)() const; // the member function pointer
};
传入的参数是一个函数指针,也就是void (Person::*_Pm) () const , 传递后 _Pm = &Print,在operator() 函数中return ((_Left.*_Pmemfun)()); _Left 也就是遍历到的Person 类对象,先找到类的函数,然后进行调用。
第二行中mem_fun_ref 接受两个参数,明显是重载的版本,它将一元函数转换为二元函数对象,而bind2nd 再将其转化为一元函数对象,即绑定了第二个参数为"person: ",跟踪源码可以看见这样的函数调用:
_Result operator()(_Ty &_Left, _Arg _Right) const
{
// call function with operand
return ((_Left.*_Pmemfun)(_Right));
}
也就是将第二个参数当作参数传递给PrintWithPrefix,所以打印出来的带有前缀person: 而mem_fun 就类似了,只不过此次for_each 遍历得到的是对象指针,所以进行函数调用时需要用-> 操作符,如下所示:
_Result operator()(const _Ty *_Pleft) const
{
// call function
return ((_Pleft->*_Pmemfun)());
}
_Result operator()(const _Ty *_Pleft, _Arg _Right) const
{
// call function with operand
return ((_Pleft->*_Pmemfun)(_Right));
}
(二)、针对一般函数的函数适配器:ptr_fun
1、示例1:
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
char *a[] = {"", "BBB", "CCC"};
vector<char *> v(a, a + 2);
vector<char *>::iterator it;
it = find_if(v.begin(), v.end(), bind2nd(ptr_fun(strcmp), "")); //查看不是空串的第一个串
if (it != v.end())
cout << *it << endl;
return 0;
}
运行结果:ptr_fun 将strcmp 二元函数转换为二元函数对象,bind2nd 再将其转化为一元函数对象,即绑定了第二个参数,因为strcmp 是在比较不相等的情况返回为真,故find_if 查找的是第一个不等于空串的串位置。
例程2:
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
using namespace std;
bool check(int elem)
{
return elem < 3;
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5};
vector<int> v(a, a + 5);
vector<int>::iterator it;
it = find_if(v.begin(), v.end(), not1(ptr_fun(check)));
if (it != v.end())
cout << *it << endl;
return 0;
}
运行结果:
这些代码的跟踪就留给大家自己完成了,篇幅所限,不能将所有调用过程都显现出来,学习STL还是得靠大家跟踪源码,才能有更深的体会。
参考:
C++ primer 第四版
Effective C++ 3rd
C++编程规范
C++ Primer 学习笔记_53_STL剖析(八):函数适配器:bind2nd 、mem_fun_ref 、函数适配器应用举例
标签:
原文地址:http://blog.csdn.net/keyyuanxin/article/details/50696770