STL之bind1st

1.unary_function

即一元函数

在vs2008自带的STL库中,它的定义如下

 

template
  struct unary_function {
    typedef Arg argument_type;
    typedef Result result_type;
  };

 

为什么叫一元函数呢?看一下它的使用方法就清楚了

struct IsOdd : public unary_function

{
  bool operator() (int number)

  {

      return (number%2==1);

  }
};

 

就是说,unary_function的子类的函数对象只接收一个参数

bool operator() (int number)中的int number

"this operator() member function takes one single parameter"

 

unary_function测试代码如下

 

#include #include using namespace std; struct IsOdd : public unary_function { bool operator() (int number) {return (number%2==1);} }; void TestUnaryFunc() { IsOdd IsOdd_object; IsOdd::argument_type input; IsOdd::result_type result; cout << "Please enter a number: "; cin >> input; result = IsOdd_object (input); cout << "Number " << input << " is " << (result?"odd":"even") << "./n"; }

 

 

2.binary_function

二元函数对象,由上易知这个函数对象有两个参数

见它的定义

template     class _Arg2,
    class _Result>
    struct binary_function
    {    // base class for binary functions
    typedef _Arg1 first_argument_type;
    typedef _Arg2 second_argument_type;
    typedef _Result result_type;
    };

 

“In the case of binary function objects, this operator() member function takes two parameters.”

 

TestBinaryFunc()测试代码如下

//TestBinaryFunc.cpp //这段代码源于cplusplus #include #include using namespace std; struct Compare : public binary_function { bool operator() (int a, int b) {return (a==b);} }; void TestBinaryFunc() { Compare Compare_object; Compare::first_argument_type input1; Compare::second_argument_type input2; Compare::result_type result; cout << "Please enter first number: "; cin >> input1; cout << "Please enter second number: "; cin >> input2; result = Compare_object (input1,input2); cout << "Numbers " << input1 << " and " << input2; if (result) cout << " are equal./n"; else cout << " are not equal./n"; }

 

 

3.bind1st

看完了1和2,bind1st就很容易理解了。它先利用binary_function,先绑定一个

参数,然后像使用一元函数对象那样使用binary_function

 

以下是bind1st的部分代码

  binder1st(const _Fn2& _Func,
        const typename _Fn2::first_argument_type& _Left)
        : op(_Func), value(_Left)
        {    // construct from functor and left operand
        }

//_Left绑定了一个参数

//_Func一个二元函数对象

 

//这样就实现了像使用一元函数对象那样使用二元函数对象了

    result_type operator()(const argument_type& _Right) const
        {    // apply functor to operands
        return (op(value, _Right));
        }

 

bind1st测试代码如下

//TestBind1st.cpp #include #include #include using namespace std; void TestBind1st() { int numbers[] = {10,20,30,40,50,10}; int cx; cx = count_if (numbers, numbers+6, bind1st(equal_to(),10) ); cout << "There are " << cx << " elements that are equal to 10./n"; }

 

TestBind2nd就好理解了。它绑定了二元函数对象的第二个参数

你可能感兴趣的:(C++)