STL中list实现降序排列

来源:互联网 发布:软件实施顾问岗位职责 编辑:程序博客网 时间:2024/06/05 06:36
       STL list可以对基本数据、字符串直接调用sort()函数默认做升序排列,但是对于降序排列或者对非基本数据类型排序(对象、数组等)需要借助operator()函数实现,这点和Java中的List很相似。
具体调用函数:
list.sort(Cmpare());

其中Cmpare是一个类或结构体,成员函数operator()必须是公共类型的。

我举一个简单的例子(对学生按年龄降序排列)

  

[cpp] view plaincopy
  1. #ifndef _STUDENT_H_  
  2. #define _STUDENT_H_  
  3. #include <string>  
  4. using namespace std;  
  5. class Student   
  6. {  
  7. private:  
  8.     int age;  
  9.     string name;  
  10. public:  
  11.     void setAge(int age);  
  12.     void setName(string name);  
  13.     int getAge() const;   
  14.     string getName() const;  
  15. };  
  16.   
  17. #endif  
  18.   
  19.   
  20. #include "Student.h"  
  21. void Student::setAge(int age)  
  22. {  
  23.     this->age = age;  
  24. }  
  25.   
  26. void Student::setName(string name)   
  27. {  
  28.     this->name = name;  
  29. }  
  30.   
  31. int Student::getAge() const  
  32. {  
  33.     return this->age;  
  34. }  
  35.   
  36. string Student::getName() const  
  37. {  
  38.     return this->name;  
  39. }  
  40.   
  41.   
  42.   
  43. #ifndef _CMPARE_H_  
  44. #define _CMPARE_H_  
  45. #include "Student.h"  
  46. class Cmpare  
  47. {  
  48. public:  
  49.     bool operator()(const Student st1,const Student  st2) const;  
  50. };  
  51. #endif  
  52.   
  53.   
  54. #include "Cmpare.h"  
  55. bool Cmpare::operator()(const Student st1,const Student  st2) const   
  56. {  
  57.     return st1.getAge() > st2.getAge();     
  58. }  
  59.   
  60.   
  61. #include "stdafx.h"  
  62. #include <stdlib.h>  
  63. #include <list>  
  64. #include <iostream>  
  65. #include "Cmpare.h"  
  66. using namespace std;  
  67.   
  68. int _tmain(int argc, _TCHAR* argv[])  
  69. {  
  70.       
  71.     Student stu1;  
  72.     stu1.setAge(20);  
  73.     stu1.setName("stu1");  
  74.   
  75.     Student stu2;  
  76.     stu2.setAge(18);  
  77.     stu2.setName("stu2");  
  78.       
  79.     Student stu3;  
  80.     stu3.setAge(17);  
  81.     stu3.setName("stu3");  
  82.   
  83.     Student stu4;  
  84.     stu4.setAge(22);  
  85.     stu4.setName("stu4");  
  86.   
  87.     list<Student> stuList;  
  88.     stuList.push_back(stu1);  
  89.     stuList.push_back(stu2);  
  90.     stuList.push_back(stu3);  
  91.     stuList.push_back(stu4);  
  92.   
  93.    stuList.sort(Cmpare());  
  94.   
  95.    list<Student>::iterator stuIter = stuList.begin();  
  96.    for( ; stuIter != stuList.end() ; stuIter ++)   
  97.    {  
  98.        cout<<"name:"<<(*stuIter).getName() <<",age:"<<(*stuIter).getAge()<<endl;  
  99.    }  
  100.    return 0;  
  101. }  

运行结果:
    name:stu4,age:22
     name:stu1,age:20
     name:stu2,age:18
     name:stu3,age:17

0 0
原创粉丝点击