C++ STL源码分析——适配器之仿函数适配器 bind2nd 以及 bind

【侯捷-SL体系结构内核分析-适配器】bind2nd 为二元函数适配器,指定二元函数的第二个参数,将二元函数转变为一元函数。比如下面这个例子:int main(){ vector<int> vec = vector<int>{ 4, 5 ,6 ,3, 5 ,8 ,3 }; int count = count_if(vec.begin(), vec.end(), b...
摘要由CSDN通过智能技术生成

【侯捷-SL体系结构内核分析-适配器】

bind2nd 为二元函数适配器,指定二元函数的第二个参数,将二元函数转变为一元函数。比如下面这个例子:

int main()
{
   
	vector<int> vec = vector<int>{
    4, 5 ,6 ,3, 5 ,8 ,3 };
	int count = count_if(vec.begin(), vec.end(), bind2nd(less<int>(), 5));
	cout << count << endl;
	return 1;
}

less 函数为比较两个参数的大小,需要传入两个参数。这里利用 bind2nd 仿函数适配器,将 less 的第二个参数固定为 5,此时 count_if 就会返回容器中元素小于5的元素个数。

注意:

  • less<int>() 创建了一个临时的 less<int> 对象。

源码

template<class _Fn,
	class _Ty>
	_NODISCARD inline binder2nd<_Fn> bind2nd(const _Fn& _Func, const _Ty& _Right)
	{
   	// return a binder2nd functor adapter
	typename _Fn::second_argument_type _Val(_Right);
	return (binder2nd<_Fn>(_Func, _Val))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值