題目
例 2.2 成績排序 (九度教程第 2 題)
時間限制:1 秒
內存限制:32 兆 特殊判題:否
題目描述:
有 N 個學生的數據,將學生數據按成績高低排序,如果成績相同則按姓名
字符的字母序排序,如果姓名的字母序也相同則按照學生的年齡排序,並輸出 N
個學生排序後的信息。
輸入:
測試數據有多組,每組輸入第一行有一個整數 N(N<=1000),接下來的 N
行包括 N 個學生的數據。每個學生的數據包括姓名(長度不超過 100 的字符串) 、
年齡(整形數)、成績(小於等於 100 的正數)。
輸出:
將學生信息按成績進行排序,成績相同的則按姓名的字母序進行排序。然後
輸出學生信息,按照如下格式:姓名 年齡 成績
樣例輸入:
3
abc 20 99
bcd 19 97
bed 20 97
樣例輸出:
bcd 19 97
bed 20 97
abc 20 99
提示:
學生姓名的字母序區分字母的大小寫,如 A 要比 a 的字母序靠前(因爲 A 的
ASC 碼比 a 的 ASC 碼要小)。
來源:
2000 年清華大學計算機研究生機試真題
思路
之前做的都是純數字排序題,這次是一組信息,按要求比較排序,王道考研機試指南用的是c語言的結構體完成的,我準備用c++的類成員實現。這道題中的比較字符串需要調用string.h中的strcmp函數,另外對於三個層次的排序要求另外寫一個bool類型的函數cmp, 作爲參數放在sort中。
一旦建立了 cmp 函數,該函數便可作爲計算機對其進行排序的依據,所以我們依然可以使用 sort 函數對其進行快速排序,但是不要忘記,將 sort 的第三個參數設定爲 cmp 函數,使 sort 函數知道該應用什麼規則對其進行定序。
代碼
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
class Student
{
public:
void getInf(){cin >> name >> age >> score;}
void showInf(){cout << name << " " << age << " " << score << endl;}
char name[100];
int age;
int score;
};
bool cmp(Student s1, Student s2)
{
if(s1.score != s2.score) return s1.score < s2.score;
int temp = strcmp(s1.name, s2.name); //用strcmp實現字符串比較
if(temp != 0) return temp < 0;
if(s1.age != s2.age) return s1.age < s2.age;
}
int main()
{
int n;
while(cin >> n)
{
Student stu[n];
for(int i = 0; i < n; i ++) stu[i].getInf();
sort(stu, stu + n, cmp);
for(int j = 0; j < n; j ++) stu[j].showInf();
}
return 0;
}
遇到的問題以及解決辦法
- Student stu[n];這句話一開始放在了主函數內while循環之外,導致結果錯誤。
- 數據成員char name[100];一開始定義爲了char*,導致結果錯誤。但是我不知道爲什麼錯了,於是進行了測試:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char *a, *b;
cin >> a >> b;
return 0;
}
分析之後可能是因爲字符指針沒有分配內存空間就直接賦值,這樣不行。於是改進:
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
const int maxlength=100;
char *a=(char *)malloc(maxlength*sizeof(char));
char *b=(char *)malloc(maxlength*sizeof(char));
cin >> a >> b;
cout << a << " " << b;
return 0;
}
成了。