STL list可以对基本数据、字符串直接调用sort()函数默认做升序排列,但是对于降序排列或者对非基本数据类型排序(对象、数组等)需要借助operator()函数实现,这点和Java中的List很相似。
具体调用函数:
list.sort(Cmpare());
具体调用函数:
list.sort(Cmpare());
其中Cmpare是一个类或结构体,成员函数operator()必须是公共类型的。
我举一个简单的例子(对学生按年龄降序排列):
#ifndef _STUDENT_H_
#define _STUDENT_H_
#include <string>
using namespace std;
class Student
{
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
{
return this->age;
}
string Student::getName() const
{
return this->name;
}
#ifndef _CMPARE_H_
#define _CMPARE_H_
#include "Student.h"
class Cmpare
{
public:
bool operator()(const Student st1,const Student st2) const;
};
#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"
using namespace 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