posts - 0,  comments - 0,  trackbacks - 0
      今天翻看STL中的Functional头文件,文件中定义了一些常用的函数对象(顾名思义,就是定义重载()运算符,让一个类向一个函数一样去用)。
      首先定义了一个结构体来作为其它结构体的基类,实际上这个结构体只是提供了统一的类型名以使其他的类来继承。
      一元结构体模板定于如下:
     template<class _A, class _R>
       struct unary_function {
          typedef _A argument_type;
          typedef _R result_type;
       };      
        模板参数的定义应该能够看出来,其中之一是输入的参数,另一个是输出结果。二元的话,就不用说了,只不过比一元的多了一个输入参数而已:
   template<class _A1, class _A2, class _R>
       struct binary_function {
          typedef _A1 first_argument_type;
          typedef _A2 second_argument_type;
          typedef _R result_type;
      };
   
      下面看看其他的函数对象如何去定义,以greater为例。   
   template<class _Ty>
       struct greater : binary_function<_Ty, _Ty, bool> {
             bool operator()(const _Ty& _X, const _Ty& _Y) const
              {
                     return (_X > _Y); 
               }
       };
      以STL中的sort为例,首先定义一个数组
      int a[5] = {2,4,1,3,5};
      sort(&a[0],&a[5]);
      输出结果应该为1,2,3,4,5.
      但是如果用函数对象greater来作为sort的第三个参数:
      sort(&a[0],&a[5],greater<int>());
      那么输出结果就变成了5,4,3,2,1.
      也就是sort内部的比较方式采用了greater来比较。

         为了充分理解函数对象,自定义一个结构体,继承自binary_function ,用以按照绝对值的大小来排序。
       template<class T>
      struct AbsoluteLess : public binary_function<T,T,bool>
      {
             bool operator() (T x ,T y) const
              {
                     return abs(x) > abs(y);
              }
      };

      然后在冒泡排序中使用这个函数对象,
      冒泡排序如下:
      template<class T,class CompareType>
      void Bubble_Sort(T *p,int size,const CompareType& Compare)
      {
          for (int i=0;i<size;++i)
          {
              for (int j= i+1;j<size;++j)
              {
                  if(Compare(p[i],p[j]))
                  {
                      const T temp = p[i];
                      p[i] = p[j];
                      p[j] = temp;
                  }
              }
          }
      }

      测试程序如下:
      int main()
   {
          double a[7] = {-100.77,-40.2,50.4,23.6,67.1,-10.3,11.8};
          int size = sizeof(a)/sizeof(double);
          Bubble_Sort(a,size,greater<double>());
          Display(a,size);
          Bubble_Sort(a,size,AbsoluteLess<double>());
          Display(a,size);
          return 0;
   }

     输出结果:
      Bubble_Sort(a,size,greater<double>())  :                 67.1      50.4      23.6      11.8     -10.3     -40.2   -100.77
      Bubble_Sort(a,size,AbsoluteLess<double>())      :  -10.3      11.8      23.6     -40.2      50.4      67.1   -100.77
posted on 2008-05-02 17:45 zhangzhiwi 阅读(98) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理


<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(1)

文章档案

搜索

  •  

最新评论