有N个学生的数据,将学生数据按成绩从高到低排序,如果成绩相同则按姓名字符的字典序排序,如果姓名的字典序也相同则按照学生的年龄从小到大排序,并输出N个学生排序后的信息。
输入描述:
测试数据有多组,每组输入第一行有一个整数N(N<=1000),接下来的N行包括N个学生的数据。
每个学生的数据包括姓名(长度不超过100的字符串)、年龄(整形数)、成绩(小于等于100的正数)。
输出描述:
将学生信息按成绩进行排序,成绩相同的则按姓名的字母序进行排序。
然后输出学生信息,按照如下格式:
姓名 年龄 成绩
学生姓名的字母序区分字母的大小写,如A要比a的字母序靠前(因为A的ASC码比a的ASC码要小)。
示例1
输入
3
abc 20 99
bcd 19 97
bed 20 97
输出
bcd 19 97
bed 20 97
abc 20 99
解题思路:
定义保存学生信息的结构体:
struct s {
char name[101];
int age;
int sore;
};// student[1000];
struct s student[1000];
struct s {
char name[101];
int age;
int sore;
}student[1000];
第二种情况下可直接创建结构体数组。
AC代码:
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
using namespace std;
struct s {
char name[101];
int age;
int sore;
};// student[1000];
struct s student[1000];
bool rule(s a, s b) {//排序规则
if (a.sore != b.sore) return a.sore < b.sore;
int flag = strcmp(a.name, b.name);
if (flag == 0) return a.age < b.age;
else return flag < 0 ;
}
int main() {
int n;
while (cin >> n) {
for (int i = 0; i < n; i++) {
cin >> student[i].name >> student[i].age >> student[i].sore;
}
sort(student, student + n, rule);
for (int i = 0; i < n; i++) {
cout<< student[i].name <<" " << student[i].age <<" "<< student[i].sore<<endl;
}
}
//system("pause");
return 0;
}
strcmp()函数使用
头文件:#include<string.h>
语法/原型:
int strcmp(const char* str1,const char* str2);
参数 str1 和 str2 是参与比较的两个字符串。
说明:strcmp()函数是根据ACSII码的值来比较两个字符串的;strcmp()函数首先将str1字符串的第一个字符值减去str2的第一个字符,若差值为零则继续比较下去;若差值不为零,则返回差值。
返回值:
如果返回值 < 0,则表示 str1 小于 str2。
如果返回值 > 0,则表示 str2 小于 str1。
如果返回值 = 0,则表示 str1 等于 str2。
程序输入:
3
abc 1 1
ac 1 1
abcd 1 1
比较结果:
abc 1 1
abcd 1 1
ac 1 1