定义一个学生结构体类型student,包括4个字段,姓名、性别、年龄和成绩。然后在主函数中定义一个结构体数组(长度不超过1000),并输入每个元素的值,程序使用冒泡排序法将学生按照成绩从小到大的顺序排序,然后输出排序的结果。
输入格式:第一行是一个整数N(N<1000),表示元素个数;接下来N行每行描述一个元素,姓名、性别都是长度不超过20的字符串,年龄和成绩都是整型。
输出格式:按成绩从小到大输出所有元素,若多个学生成绩相同则成绩相同的同学之间保留原来的输入顺序。
输入:
3
Alice female 18 98
Bob male 19 90
Miller male 17 92
输出:
Bob male 19 90
Miller male 17 92
Alice female 18 98
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct student {
string name;
string sex;
int age;
int score;
};
bool cmp(student a, student b) { //注意这里排序 分数相同,男性优先,分数性别相同,学号小优先
if (a.score != b.score)
return a.score < b.score;
else if (a.sex != b.sex)
return a.sex > b.sex;
else
return a.name < b.name;
}
int main() {
int n;
cin >> n;
vector<student> stu(n);
for (int i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].sex >> stu[i].age >> stu[i].score;
}
sort(stu.begin(), stu.end(),cmp);
for (int i = 0; i < n; i++) {
cout << stu[i].name<<" " << stu[i].sex<<" " << stu[i].age <<" "<< stu[i].score<<endl;
}
cin >> n;
return 0;
}