STL中list實現降序排列
阿新 • • 發佈:2019-01-10
STL list可以對基本資料、字串直接呼叫sort()函式預設做升序排列,但是對於降序排列或者對非基本資料型別排序(物件、陣列等)需要藉助operator()函式實現,這點和Java中的List很相似。
具體呼叫函式:
list.sort(Cmpare());
具體呼叫函式:
list.sort(Cmpare());
其中Cmpare是一個類或結構體,成員函式operator()必須是公共型別的。
我舉一個簡單的例子(對學生按年齡降序排列):
- #ifndef _STUDENT_H_
- #define _STUDENT_H_
- #include <string>
- usingnamespace std;
-
class
- {
- private:
- int age;
- string name;
- public:
- void setAge(int age);
- void setName(string name);
- int getAge() const;
- string getName() const;
- };
- #endif
- #include "Student.h"
- void Student::setAge(int age)
- {
- this->age = age;
- }
-
void Student::setName(string name)
- {
- this->name = name;
- }
- int Student::getAge() const
- {
- returnthis->age;
- }
- string Student::getName() const
- {
- returnthis->name;
- }
- #ifndef _CMPARE_H_
- #define _CMPARE_H_
- #include "Student.h"
- class Cmpare
- {
- public:
-
bool operator()(const Student st1,const Student st2)
- };
- #endif
- #include "Cmpare.h"
- bool Cmpare::operator()(const Student st1,const Student st2) const
- {
- return st1.getAge() > st2.getAge();
- }
- #include "stdafx.h"
- #include <stdlib.h>
- #include <list>
- #include <iostream>
- #include "Cmpare.h"
- usingnamespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- Student stu1;
- stu1.setAge(20);
- stu1.setName("stu1");
- Student stu2;
- stu2.setAge(18);
- stu2.setName("stu2");
- Student stu3;
- stu3.setAge(17);
- stu3.setName("stu3");
- Student stu4;
- stu4.setAge(22);
- stu4.setName("stu4");
- list<Student> stuList;
- stuList.push_back(stu1);
- stuList.push_back(stu2);
- stuList.push_back(stu3);
- stuList.push_back(stu4);
- stuList.sort(Cmpare());
- list<Student>::iterator stuIter = stuList.begin();
- for( ; stuIter != stuList.end() ; stuIter ++)
- {
- cout<<"name:"<<(*stuIter).getName() <<",age:"<<(*stuIter).getAge()<<endl;
- }
- return 0;
- }
執行結果:
name:stu4,age:22
name:stu1,age:20
name:stu2,age:18
name:stu3,age:17