C++ STL set自定义比较函数

来源:互联网 发布:天梯金融 淘宝 编辑:程序博客网 时间:2024/06/10 03:08

C++ STL 容器很多都可以自定义比较函数,给容器调用,对其中的子项做排序。下面是一个小例子:

[cpp] view plaincopy
  1. #include <set>  
  2. #include <string>  
  3. #include <iostream>  
  4.   
  5. using namespace std;  
  6.   
  7. class CTest {  
  8. public:  
  9.         CTest() { num = 0; str = ""; }  
  10.         CTest(int _num, string _str) { num = _num; str = _str; }  
  11.         string str;  
  12.         int num;  
  13. };  
  14.   
  15. class CTestCmp {  
  16. public:  
  17.         bool operator() (const CTest& lc, const CTest& rc) {  
  18.                 //return !!(lc.num < rc.num);  
  19.                 return !!(lc.str < rc.str);  
  20.         }  
  21. };  
  22.   
  23. typedef set<CTest, CTestCmp> CTestSet;  
  24.   
  25. void OutputCTestSet(const CTestSet &_set) {  
  26.         cout << "Set [" << endl;  
  27.         for(CTestSet::iterator it = _set.begin(); it != _set.end(); ++it) {  
  28.                 cout << "str:" << it->str << ", num:" << it->num << endl;  
  29.         }  
  30.         cout << "]" << endl;  
  31. }  
  32.   
  33. int main(int argc, char* argv[])  
  34. {  
  35.         CTestSet _set;  
  36.         _set.insert(CTest(2, "hello"));  
  37.         _set.insert(CTest(1, "world"));  
  38.         _set.insert(CTest(3, "blowing"));  
  39.         OutputCTestSet(_set);  
  40.   
  41.         return 0;  
  42. }  

ln 15定义比较函数类,ln 23申明使用了这个比较类的set类型,main()函数中给该类型的对象放入三个子项,然后依次输出。

放开ln 19,屏蔽ln 18,输出:(按str属性升序排列)

[plain] view plaincopy
  1. Set [  
  2. str:blowing, num:3  
  3. str:hello, num:2  
  4. str:world, num:1  
  5. ]  

放开ln 18,屏蔽ln 19,输出:(按num属性升序排列)

[plain] view plaincopy
  1. Map [  
  2. str:world, num:1  
  3. str:hello, num:2  
  4. str:blowing, num:3  
  5. ]  

注意,ln 18或ln 19,使用 (left < right) 的比较方式,排序方式就是升序,即从小到大;反之,如果用 (left > right),将降序、从大到小排序。
0 1
原创粉丝点击