现在的位置: 首页 > 综合 > 正文

STL配接器:

2018年10月03日 ⁄ 综合 ⁄ 共 2215字 ⁄ 字号 评论关闭

一、配接器定义

      配接器没有找到合适的定义,在网上搜到了一下两种说法,作为定义:

      1. 配接器是一种设计模式,它在原有类型的基础上扩展成为另一个接口,使原本因为接口不兼容而不能合作的类型可以一起工作。

      2. 函数对象直接应用的地方较少,它配合实现一些算法(作为算法的参数),于是便有函数配接器。

二、配接器应用实例

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


int main(int argc, char *argv[])
{
	int arr[] = {11, 12, 13, 1, 2, 3, 4, 5, 6, 7};
	
	vector<int> vec(arr, arr+10);
	cout<<count_if(vec.begin(), vec.end(), bind1st(less<int>(), 10))<<endl;  //输出3
	cout<<count_if(vec.begin(), vec.end(), bind2nd(less<int>(), 10))<<endl;  //输出7

	return 1;
};

三、配接器的理解

3.1 bind2nd、binder2nd源码

/*摘自C++ standard STL。*/ 
// 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 
};


// 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)); 
}

3.2 bind2nd、binder2nd源码说明

      1. bind2nd()是辅助函数,为的是使用binder2nd(真正的主角)更方便。

      2. count_if(vec.begin(), vec.end(), bind2nd(less<int>(), 10))中less<int>在binder2nd函数对象的构造函数中被作为其内部操作成员(它是一个函数对象)_Fn2 op;

      3. count_if()函数在处理每一个元素的时候,实际调用bindeer2nd的"()"运算符重载函数,而这个函数当中又调用了其内部操作成员op(其又是一个函数对象less<int>)的"()"运算符重载函数。 如此一来,配接就成功了。其他的函数配接器做法类似。

      总结,count_if()调用bind2nd()函数,bind2nd()函数实际产生binder2nd函数对象,返回给count_if()作为参数,count_if()再调用更为底层的函数_Count_if()函数。

参考资料:

      配接器定义:http://www.cnblogs.com/whyandinside/archive/2012/10/14/2723500.html

      配接器理解:http://www.cfanz.cn/index.php?c=article&a=read&id=38289

      STL的各配接器及其应用:http://www.360doc.com/content/12/1209/14/9290626_253022276.shtml

抱歉!评论已关闭.