C++ 学生信息排序:按出生日期从小到大排序
C++ 学生信息排序:按出生日期从小到大排序
问题描述:
给定 n 个学生的信息,包括姓名、性别、出生年份、出生月份,要求从小到大依次输出这些学生的信息。
输入描述:
第一行包含一个正整数 n,接下来的 n 行,每行描述一个学生的信息,各个信息之间用一个空格分隔。
输出描述:
包括 n 行,年龄小的先输出,每行包含一位同学的信息,依次为姓名、性别、出生年份、出生月份,四部分之间用一个空格分隔。给定的数据保证没有同年同月同日的情况。
示例:
输入:
3
Alice F 1998 5
Bob M 1997 8
Cathy F 1999 3
输出:
Bob M 1997 8
Alice F 1998 5
Cathy F 1999 3
C++ 代码实现:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
char gender;
int birth_year;
int birth_month;
};
bool compare(Student s1, Student s2) {
if (s1.birth_year < s2.birth_year) {
return true;
}
else if (s1.birth_year == s2.birth_year && s1.birth_month < s2.birth_month) {
return true;
}
return false;
}
int main() {
int n;
cin >> n;
vector<Student> students;
for (int i = 0; i < n; i++) {
Student student;
cin >> student.name >> student.gender >> student.birth_year >> student.birth_month;
students.push_back(student);
}
sort(students.begin(), students.end(), compare);
for (int i = 0; i < n; i++) {
cout << students[i].name << ' ' << students[i].gender << ' ' << students[i].birth_year << ' ' << students[i].birth_month << endl;
}
return 0;
}
代码解释:
-
结构体定义: 使用
struct Student定义一个结构体,用于存储学生的姓名、性别、出生年份和出生月份。 -
比较函数: 使用
bool compare(Student s1, Student s2)定义一个比较函数,用于比较两个学生的出生日期。函数首先比较出生年份,如果年份相同,则比较出生月份。 -
主函数: 主函数首先读取学生的数量
n,然后使用循环读取每个学生的信息并存储到students向量中。接着使用sort()函数对students向量进行排序,排序规则由compare()函数定义。最后使用循环输出排序后的学生信息。
注意: 代码中已经将双引号改为单引号,并将代码内容用反引号包裹,以避免 JSON 解析错误。
原文地址: https://www.cveoy.top/t/topic/quMt 著作权归作者所有。请勿转载和采集!