Bind2nd源码解析

例如:

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

int main(int argc, char *argv[])
{
	vector<int> coll{ 1, 3, 5, 7, 9, 11, 13, 15 };
	// 接着下面有bind2nd的具体实现
	cout << count_if(coll.begin(), coll.end(), 
					bind2nd(greater<int>(), 10)) << endl;
	return 0;
}

运行结果为:3
返回大于10的数字的个数,共3个。
1、调用模板函数bind2nd,第一个参数为greater临时对象。

// 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 (binder2nd<_Fn2>(_Func, _Val));
}

2、模板类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
};

3、模板类binder2nd模板基类unary_function的定义:

// TEMPLATE STRUCT unary_function
template<class _Arg, class _Result>
struct unary_function
{	
	// base class for unary functions
	typedef _Arg argument_type;
	typedef _Result result_type;
};

4、仿函数greater的定义

// TEMPLATE STRUCT greater
template<class _Ty = void>
struct greater
{	
	// functor for operator>
	typedef _Ty first_argument_type;
	typedef _Ty second_argument_type;
	typedef bool result_type;

	constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const
	{	
		// apply operator> to operands
		return (_Left > _Right);
	}
};

参考:https://www.cnblogs.com/ggzone/p/4052441.html
https://www.cnblogs.com/runnyu/p/6010101.html
https://blog.csdn.net/wk_bjut_edu_cn/article/details/80004279

count_if的用法:https://blog.csdn.net/m0_38033475/article/details/79561369

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值