例如:
#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