unary_function 和 binary_function

1.  unary_function:
    unary_function的定义如下:
template<class Arg, class Result>
struct unary_function
{
    typedef Arg argument_type;
    typedef Result result_type;
};
unary_function可以作为一个一元函数对象的基类,他定义了两个模板参数,分别是函数参数类型argument_type和返回值类型result_type,本身并不重载函数符(),由派生类去完成()操作符的重载工作。
 
2.  binary_function:
    binary_function的定义如下:
template<class Arg1, class Arg2, class Result>
struct binary_function
{
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
};
binary_function可以作为一个二元函数对象的基类,他定义了三个模板参数,两个函数参数类型first_argument_type和second_argument_type,以及返回值类型result_type,本身并不重载函数符(),由派生类去完成()操作符的重载工作。
 
3. binary_function使用例子:
  构造一个继承binary_function的派生类,作为set容器的比较类型( 实现greater<double> )
#include <iostream>
#include <cstring>
#include <set>
#include <algorithm>
#include <functional>

using namespace std;

struct GreaterNum : public binary_function<double,double,bool>
{
    bool operator()(double x, double y)
    {
        return x>y;
    }
};

void print(double x)
{
    cout<<x<<endl;
}

int main()
{
    set<double,GreaterNum> sd;
    sd.insert(3.13);
    sd.insert(4.13);
    sd.insert(1.13);
    sd.insert(0.63);
    sd.insert(9.15);
    sd.insert(0.03);
    for_each(sd.begin(), sd.end(), print);
    return 0;
}

 

转载于:https://www.cnblogs.com/ladawn/p/8318506.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值