【侯捷-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))