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;
}

 

posted @ 2018-01-19 19:15  IvanB.G.Liu  阅读(1014)  评论(0)    收藏  举报