默认的sort函数是按升序排
sort(a,a+n);
两个参数分别为待排序数组的首地址和尾地址
STL中 sort 默认是字典序升序,如果我们要改变排序顺序,那么就可以使用 sort 的第三个参数:
如果希望a数组
中的元素从大到小排列(或按照某一个规则进行排列),我们可以再为sort
传入第三个参数——“排序方法”
sort(a, a + 5, greater<int>());
其中,greater
表示“更大”的意思,<int>
表示待排序的数组中的元素类型为int
,整个这行代码表示让一个元素类型为整数的数组从大到小排序。
此时程序为:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[] = { 3, 4, 5, 2, 1 };
sort(a, a + 5, greater<int>());
return 0;
}
结构体中排序的用法
将 sort 的用法时,我们延申一下结构体:
结构体的构造函数
struct Student{
string name;
int score;
Student(){}
Student(string n, int s):name(n), score(s){}
};
除此之外,我们可以对结构体进行排序:
我们要达成的目的有两个:
1. 根据学生名字的字典序升序排序
2. 根据学生的成绩排序,若第一科成绩相同则看第二课成绩,依次类推
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
struct Student {
string name;
int score[4];
};
bool cmp_name(Student x,Student y){
return x.name < y.name;
}
bool cmp_score(Student x, Student y){
if(x.score[0] != y.score[0]){
return x.score[0] > y.score[0];
}
if(x.score[1] != y.score[1]){
return x.score[1] > y.score[1];
}
if(x.score[2] != y.score[2]){
return x.score[2] > y.score[2];
}
return x.score[3] > y.score[3];
}
int main() {
Student stu[3];
for (int i = 0; i < 3; i++) {
cin >> stu[i].name;
for (int j = 0; j < 4; j++) {
cin >> stu[i].score[j];
}
}
sort(stu, stu + 3, cmp_name);
for (int i = 0; i < 3; i++) {
cout << stu[i].name << ":";
for (int j = 0; j < 4; j++) {
cout << stu[i].score[j] << " ";
}
cout<<endl;
}
sort(stu, stu + 3, cmp_score);
for (int i = 0; i < 3; i++) {
cout << stu[i].name << ":";
for (int j = 0; j < 4; j++) {
cout << stu[i].score[j] << " ";
}
cout<<endl;
}
return 0;
}
有一点特别要注意——那就是不能用 typedef 的同时去声明一个结构体数组
如下:
typedef struct Student{
string name;
int a, b, c, d;
}stu[50];
这样会报出 [Error] expected primary-expression before '[' token 的错误