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

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

[cpp]  view plain copy
  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 plain copy
  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 plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值