sort()函数:是c++ stl库中的一个排序函数,学会使用这个函数可以大大节省我们自己去写一个排序函数,如:冒泡排序(O(n2))等,而且这个排序函数是用快速排序写的,故时间复杂度为O(nlogn),因此还能大大减少程序运行时间。
注意,它排序的范围是 [first, last)[,包括 first,不包括 last。
用法:
vector<int> a = {3,7,2,5,6,8,5,4};
sort(a.begin(),a.begin()+4); //对前4个排序,输出2 3 5 7 6 8 5 4
//sort(a.begin(),a.end()); //从小到大排序, 输出2 3 4 5 5 6 7 8
//sort(a.begin(),a.end(),less<int>()); //输出2 3 4 5 5 6 7 8
//sort(a.begin(),a.end(),my_less); //自定义排序,输出 2 3 4 5 5 6 7 8
//sort(a.begin(),a.end(),greater<int>());//从大到小排序,输出 8 7 6 5 5 4 3 2
//sort(a.begin(),a.end(),my_greater); // 输出 8 7 6 5 5 4 3 2
利用 cmp()
函数,sort()
还可以对结构体进行排序,例如:
struct Student{
char name[256];
int score; //分数
};
bool cmp(struct Student* a,struct Student* b){//按分数从大到小排序
return a->score > b->score;
}
……
vector<struct Student*> list; //定义list,把学生信息存到list里
……
sort(list.begin(), list.end(), cmp); //按分数排序
举两个简单的例子
例子1:错误票据
题目描述
某涉密单位下发了某种票据,并要在年终全部收回。
每张票据有唯一的 ID 号。全年所有票据的 ID 号是连续的,但ID的开始数码是随机选定的。
因为工