用vector配合string進行儲存,函數指針pfun根據flag值指向對應的比較函數,排序後輸出。
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
struct student {
string num;
string name;
int score = 0;
};
vector<student>v;
bool num(const student a, const student b) { if (a.num > b.num) return false; return true; }
bool name(const student a, const student b) { if (a.name > b.name || (a.name == b.name && a.num > b.num)) return false; return true;}
bool score(const student a, const student b) { if (a.score > b.score || (a.score == b.score && a.num > b.num)) return false; return true;}
int main(void)
{
int N, flag;
scanf("%d %d", &N, &flag);
bool (*pfun) (const student, const student);
if (flag == 1)pfun = num;
else if (flag == 2)pfun = name;
else pfun = score;
student s;
char num[7], name[9];
for (int i = 0; i < N; i++) {
scanf("%s %s %d", num, name, &s.score);
s.num = num;
s.name = name;
v.push_back(s);
}
sort(v.begin(), v.end(), *pfun);
for (int i = 0; i < N; i++) {
printf("%s %s %d\n", v[i].num.c_str(), v[i].name.c_str(), v[i].score);
}
return 0;
}