STL约束器原理
来源:互联网 发布:蚁群算法改进 编辑:程序博客网 时间:2024/04/29 02:29
//函数对象基类
template<class Arg, class Res>struct unary_function{
typedef Arg argument_type;
typedef Res result_type;
}
template<class Arg, class Arg2, class Res>struct binary_function{
typedef Arg first_argument_type;
typedef Arg2 second_argument_type;
typedef Res result_type;
}
//约束器
void f(list<int>& c)
{
list<int>::const_iterator p=find_if(c.begin(), c.end(), less_than<int>(7));
}
首先,less_than<int>(7)是用模板类创建了一个对象。
template<class T>class less_than : public unary_function<T, bool>{
T arg2;
public:
explicit less_than(const T& x): arg2(x) {}
bool operator()(const T& x) const { return x<arg2; }
}
则T为int类型,模板类中的成员变量arg2为7。则less_than<int>(7)即为该模板生成的一个对象,对象类型为less_than<int>。
接下来看VC中实现的find_if算法代码:
//find_if函数
template<class _II, class _Pr> inline
_II find_if(_II _F, _II _L, _Pr _P)
{for (; _F != _L; ++_F)
if (_P(*_F))
break;
return (_F); }
可知_Pr为less_than<int>类型,_P是对象less_than<int>(7)
在_P(*_F),其中_F是迭代器,则*_F指向容器元素。展开之后即为less_than<int>(7)(*_F)很明显是运算符()的重载,调用到bool operator()(const T& x) const { return x<arg2; },将x绑定到*_F的引用,从而实现了容器元素与7的比较。
//支持约束器的类
void f(list<int>& c)
{
list<int>::const_iterator p=find_if(c.begin(), c.end(), bind2nd(less<int>(), 7));
}
bind2nd(less<int>(), 7)调用到函数模板:
template<class BinOp, class T>binder2nd<BinOp> bind2nd(const BinOp& op, const T& v)
{
return binder2nd<BinOp>(op, v);
}
则BinOp为less<int>类型,T为int类型,v=7,op为less<int>(),该函数返回了一个对象:
binder2nd<less<int> >(less<int>(), 7)
binder2nd类模板如下:
template<class BinOp>class binder2nd :
public unary_function<typename BinOp::first_argument_type, typename BinOp::result_type>{
protected:
BinOp op;
typename BinOp::second_argument_type arg2;
public:
binder2nd(const BinOp& x, const typename BinOp::second_argument_type& v):op(x), arg2(v) {}
result_type operator()(const argument_type& x) const{ return op(x, arg2); }
}
在find_if中_P(*_F),这个类对象binder2nd<less<int> >(less<int>(), 7)传递给了_P,则_P(*_F)是一个运算符重载的调用。
调用 result_type operator()(const argument_type& x) const{ return op(x, arg2);
展开来看即为less<int>()(x, arg2),又调用到了less模板中的()重载运算符。如下:
template<class T>struct less:public binary_function<T, T, bool>{
bool operator()(const T& x, const T& y) const {return x<y;}
}
STL约束器原理大致如此。。
- STL约束器原理
- STL中的约束器相关总结
- STL中的约束器相关总结
- STL容器的约束
- STL约束器之bind2nd(x, y)实例解析
- STL约束器之bind2nd(x, y)实例解析
- STL算法原理分析
- stl hash_map原理
- STL容器设计原理
- stl的实现原理
- STL中traits原理
- STL底层原理简介
- 差分约束----原理其实很简单
- iOS中的一些约束的原理
- STL容器的实现原理
- STL容器的实现原理
- STL中map原理解析
- STL源码剖析---红黑树原理
- 什么是gcc
- UVa 696 - How Many Knights
- DB9串口定义及含义(全)
- 一点一滴培养你的领袖气质
- 数据分析师职业介绍
- STL约束器原理
- ubuntu的hgfs下找不到共享目录!!!!
- 歼-31被指将成“搅局者” 对美军售战略一招致命
- 关于增加devhelp帮助文档(转)
- 基于Struts 2开发Web应用
- 用Devhelp看自己的文档
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (一) —— 总览
- 利用Apache Rewrite功能防盗链并且对URL重写功能进行简单介绍【转自网易】
- ubuntu mysql安装