1004 成績排名 (20分)
讀入 n(>)名學生的姓名、學號、成績,分別輸出成績最高和成績最低學生的姓名和學號。
輸入格式:
每個測試輸入包含 1 個測試用例,格式為
第 1 行:正整數 n 第 2 行:第 1 個學生的姓名 學號 成績 第 3 行:第 2 個學生的姓名 學號 成績 ... ... ... 第 n+1 行:第 n 個學生的姓名 學號 成績
其中姓名
和學號
均為不超過 10 個字符的字符串,成績為 0 到 100 之間的一個整數,這里保證在一組測試用例中沒有兩個學生的成績是相同的。
輸出格式:
對每個測試用例輸出 2 行,第 1 行是成績最高學生的姓名和學號,第 2 行是成績最低學生的姓名和學號,字符串間有 1 空格。
輸入樣例:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
輸出樣例:
Mike CS991301
Joe Math990112
1 #include <iostream>
2 #include <vector>
3 #include <string>
4 #include <cstdlib>
5 #include <algorithm>
6
7
8 using namespace std; 9
10 struct Student 11 { 12 string name; 13 string id; 14 int score; 15 }; 16 bool cmp(Student &s1,Student &s2) 17 { 18 return s1.score > s2.score; 19 } 20
21 int main() 22 { 23 int line; 24 string input; 25 cin >> line; 26 vector<Student> students; 27 for(int i = 0; i < line;++i) 28 { Student stu; 29 for(int j = 0; j < 3;++j) 30 { 31 cin >> input; 32 if(j == 0) 33 { 34 stu.name = input; 35 }else if(j == 1){ 36 stu.id = input; 37 }else if(j == 2) 38 { 39 stu.score = atoi(input.c_str()); 40 } 41 } 42 students.push_back(stu); 43 } 44 sort(students.begin(),students.end(),cmp); 45 cout << students[0].name << " " << students[0].id << endl 46 << students[line-1].name << " " << students[line-1].id << endl; 47
48
49 return 0; 50 }
一開始想用getline是一次性接收一行數據,但是覺得太麻煩了,況且每一個數據剛好都是以空格分隔開的,所以就直接用了cin。cin只能接收空格前的,例如:hello world 只能接收到hello。
這樣就直接兩個循環,外層循環行,內層循環每行的數據。
不過有一個地方比較棘手,我cin輸入接收類型是string的,但是呢成績是double,因此要用轉換類型的函數,我查資料得到兩個函數。
一個是我上文用的int atoi(const char *str)。這個函數是c函數,導入文件是#include<cstdlib>
另一個是stoi函數,定義:stoi(字符串,起始位置,n進制),將 n 進制的字符串轉化為十進制,導入文件是#include<string>
當然是第二種更好,但是我的codeblocks總是報錯,於是就用了上文的atoi,如果可編譯的話第二種是首選。