一、sort降序排列
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int x, int y);
int main() {
int n;
int data[100];
while (cin>>n) {
for (int i = 0; i < n; i++)
cin >> data[i];
sort(data, data + n, cmp);
for (int i = 0; i < n; i++)
cout << data[i];
}
}
bool cmp(int x, int y) {
return x > y; //定义排序规则
}
cmp 函数返回值 true 时表示 cmp 第一个参数将会排在第二个参数前面。
二、利用重载" < "运算符来实现结构体排序
要求是:学生数据按成绩高低排序,成绩相同按姓名字符的字母序排序,姓名字母序相同按年龄排序。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
struct E {
char name[101];
int age;
int score;
bool operator <(const E& b)const {
if (score != b.score) return score < b.score;
int tmp = strcmp(name, b.name);
if (tmp != 0) return tmp < 0;
else return age < b.age;
}
};
int main() {
int n;
E data[100];
while (cin >> n) {
for (int i = 0; i < n; i++)
cin >> data[i].name >> data[i].age >> data[i].score;
sort(data, data + n);
for (int i = 0; i < n; i++)
cout << data[i].name << data[i].age << data[i].score;
}
return 0;
}