函数类: unary_function Struct

unary_function有一个兄弟是binary_function,俩格的区别是一个为了使用一个参数输入的函数对象,另外一个适合两个输入参数的函数对象。对于STL不熟悉的人,很难理解为何好端端的函数对象, 为吗要从它们继承呢?ios


其实这是由于STL适配器的须要,简单说,若是仅仅是调用此函数对象的方法,那确实不用这些古怪的东西。不过若是您的函数对象须要灵活使用的时候,就会有问题了。咱们首先看一下下面程序。less


int main()   
{   
     vector<int> vec(10, 1);   
     int count1 = count_if(vec.begin(), vec.end(), bind2nd(less_equal<int>(),
 10));       //求容器中小于等于10的元素个数   
     int count2 = count_if(vec.begin(), vec.end(), not1(bind2nd(less_equal<in
t>(), 10))); //求容器中不小于等于10的元素个数,正好是上面函数的取反   

    cout<<count1<<' '<<count2<<endl;  //10 0   
    return 0;   
}

一元运算符negate logical_not, 其余逻辑运算符 less greater_equal等等,这些都是用模板的函数对象来实现的,因此要求函数对象都是来自同一个模板基类,才能匹配. 不然,在类型上,C++编译器是没法经过语义的, 而这些函数对象的原型也无法定义.ide

举一个源码例子:函数

 //一元操做求反   
 template <class Predicate>   
 class unary_negate: public unary_function<typename Predicate::argument_type,
 bool> {   
 protected:   
     Predicate pred;   6. public:   
     explicit unary_negate(const Predicate& x) : pred(x) {}   
     bool operator()(const typename Predicate::argument_type& x) const {   
        return !pred(x);   
    }   
 };

若是没有基类模板,这个函数子是无法子定义原型的.ui



unary_function Struct

An empty base struct that defines types that may be inherited by derived classes that provides a unary function object.
spa

template<class Arg, class Result>
   struct unary_function {
      typedef Arg argument_type;
      typedef Result result_type;
   };

Remarkscode

The template struct serves as a base for classes that define a member function of the formresult_type operator()(const argument_type&const.orm

All such derived unary functions can refer to their sole argument type as argument_type and their return type as result_type.对象

Example继承

// functional_unary_function.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

using namespace std;

// Creation of a user-defined function object
// that inherits from the unary_function base class
class greaterthan10: unary_function<int, bool>
{
public:
    result_type operator()(argument_type i)
    {
        return (result_type)(i > 10);
    }
};

int main()
{
    vector<int> v1;
    vector<int>::iterator Iter;

    int i;
    for (i = 0; i <= 5; i++)
    {
        v1.push_back(5 * i);
    }

    cout << "The vector v1 = ( " ;
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)
        cout << *Iter << " ";
    cout << ")" << endl;

    vector<int>::iterator::difference_type result1;
    result1 = count_if(v1.begin(), v1.end(), greaterthan10());
    cout << "The number of elements in v1 greater than 10 is: "
         << result1 << "." << endl;
}
The vector v1 = ( 0 5 10 15 20 25 )
The number of elements in v1 greater than 10 is: 3.

Requirements

Header: <functional>

Namespace: std

相关文章
相关标签/搜索