题目大意
这道题就是给出每个人的出生日期,让我们对他们的年龄排序,输出排序后的姓名顺序,要从大到小的。
解题思路
- 能看出来,这道题使用结构体是再好不过的了。
解题步骤
- 创建一个结构体
student,里面定义姓名、出生年份、月份、日期、还有记录输入先后次序的一个变量,一共五样东西。- 贴代码:
struct student {
string name;
int y, m, d, s;
};-
还得来一个布尔类型的函数
cmp,规定一下后面sort排序时的规则——年龄大的排前面,小的在后,如果年龄一样就按照输入的先后排序。- 贴代码:
bool cmp(student first, student second) {
if (first.y < second.y) return true;
if (first.y > second.y) return false;
if (first.m < second.m) return true;
if (first.m > second.m) return false;
if (first.d < second.d) return true;
if (first.d > second.d) return false;
if (first.s < second.s) return false;
return true;
}- 最后是主函数,不用说了。
完整 AC 代码:
#include<bits/stdc++.h>
using namespace std;
struct student {
string name;
int y, m, d, s;
};
bool cmp(student first, student second) {
if (first.y < second.y) return true;
if (first.y > second.y) return false;
if (first.m < second.m) return true;
if (first.m > second.m) return false;
if (first.d < second.d) return true;
if (first.d > second.d) return false;
if (first.s < second.s) return false;
return true;
}
int main() {
int n;
cin >> n;
student students[n];
for (int i = 0; i < n; ++i) {
cin >> students[i].name >> students[i].y >> students[i].m >> students[i].d;
students[i].s = i;
}
sort(students, students + n, cmp);
for (int i = 0; i < n; ++i) {
cout << students[i].name << endl;
}
return 0;
}