首先,声明一下,由于list基础结构是链表,不能直接用下标【】来直接取某一元素。

1、当list 中类型是int或者string类型时,直接调用sort函数,即

void ListSortTest1()
{
list<string> num;
num.push_back("10_8");
num.push_back("10_3");
num.push_back("10_2");
num.push_back("10_1");
num.push_back("10_9");
num.sort();
list<int> num1;
num1.push_back(98);
num1.push_back(90);
num1.push_back(45);
num1.push_back(10);
num1.push_back(102);
num1.sort();  

库函数int  string 类型中已经包含< 符号,这时候默认的是升序排列。当需要降序时,需要自定义compare函数,实现即sort(compare)

}

2、当list 的类型是结构体类型或者类类型时,需要自己写重载操作符<,排序实现即

class student
{
public:
int age;
student()
{}
student(int a)
{
this->age = a;
}
public:

*bool operator < (student b)
{
return this->age < b.age;
}

void ListSortTest()
{
list<student> num;
num.push_back(student(1));
num.push_back(student(5));
num.push_back(student(2));
num.push_back(student(6));
num.push_back(student(9));
num.sort();//必须重载 <操作符
// sort(num.begin(),num.end());
list<student>::iterator vi;
for (vi = num.begin(); vi != num.end(); vi++)
{
cout << vi->age << endl;
}
num.clear();
}

或者这样实现:

bool compare(const student &a, const student &b)
{
return a.age < b.age;
}

num.sort(compare);


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐