Chinaunix首页 | 论坛 | 博客
  • 博客访问: 343987
  • 博文数量: 63
  • 博客积分: 1412
  • 博客等级: 中尉
  • 技术积分: 648
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-10 23:07
文章分类

全部博文(63)

文章存档

2012年(42)

2011年(21)

我的朋友

分类: C/C++

2012-02-27 13:43:16

仿函数(Functor、Function Object)

传递给STL算法的函数型参数(functional arguement)不一定要是函数,可以是行为类

似于函数的对象,即Function Object或者Functor。

STL中大量运用了Function Object,也提供了很多预先定义的Function Object。

如果你定义了一个对象,其行为像函数,就可以拿来当函数使用。

在c语言中仿函数就是回调函数。



  1. #include <iostream>
  2. #include <string>
  3. #include <set>
  4. #include <algorithm>

  5. using namespace std;

  6. class SortCirterion
  7. {
  8. public:
  9.     //注意,一定要加const
  10.     bool operator()( const int &t1, const int &t2 ) const
  11.     {
  12.         return t1>t2;
  13.     }    
  14. };

  15. typedef set<int, SortCirterion> myset;

  16. int    main()
  17. {
  18.     myset b;

  19.     for( int i=0; i<5; i++ )
  20.     {
  21.         b.insert( i );
  22.     }

  23.     for( myset::iterator iter=b.begin(); iter!=b.end(); iter++ )
  24.     {
  25.         cout << *iter << endl;
  26.     }
  27. }
输出结果:
4 3 2 1 0

阅读(1238) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~