C++ 結構體排序練習
阿新 • • 發佈:2018-12-12
7-37 模擬EXCEL排序 (25 分)
Excel可以對一組紀錄按任意指定列排序。現請編寫程式實現類似功能。
輸入格式:
輸入的第一行包含兩個正整數N(≤105) 和C,其中N是紀錄的條數,C是指定排序的列號。之後有 N行,每行包含一條學生紀錄。每條學生紀錄由學號(6位數字,保證沒有重複的學號)、姓名(不超過8位且不包含空格的字串)、成績([0, 100]內的整數)組成,相鄰屬性用1個空格隔開。
輸出格式:
在N行中輸出按要求排序後的結果,即:當C=1時,按學號遞增排序;當C=2時,按姓名的非遞減字典序排序;當C=3時,按成績的非遞減排序。當若干學生具有相同姓名或者相同成績時,則按他們的學號遞增排序。
輸入樣例:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
輸出樣例:
000001 Zoe 60
000007 James 85
000010 Amy 90
用sort函式自帶的結構體排序功能就行,這裡方便用全域性變數
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; const int maxn = 10005; int n, c; struct stu { char num[10]; char s[10]; int score; }; stu st[maxn]; int compare(stu a, stu b) { if (c == 1) return strcmp(a.num, b.num)<0; else if (c == 2) { if (strcmp(a.s, b.s)) return strcmp(a.s, b.s)<0; else return strcmp(a.num, b.num)<0; } else { if (a.score != b.score) return a.score<b.score; else return strcmp(a.num, b.num)<0; } } int main() { scanf_s("%d %d", &n, &c); for (int i = 0; i < n; i++) //scanf_s("%s %s %d", st[i].num, st[i].s, &st[i].score); cin >> st[i].num >> st[i].s >> st[i].score; sort(st, st + n, compare); for (int i = 0; i<n; i++) printf("%s %s %d\n", st[i].num, st[i].s, st[i].score); return 0; }