2018-11-17 10:28

# 求教数据结构排序问题

s1109853011,JackieChan,CS001,85
s0308893477,MirandaLambert,HM467,35
s4045128481,SophiaPam,CM604,75
s0812340023,PhilipsChiu,CS001,71

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 1条回答默认 最新

• metaxx 2018-11-17 10:43
已采纳

可以定义一个结构体，然后自己分别定义三个按照学号姓名成绩的cmp函数，再用sort就行了。
文件操作的话就用freopen吧。
以下是个人代码，不足之处，请指正。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
using namespace std;

const int MAXN = 100 + 5;

struct student {
string id;
string name;
int score;
}s[MAXN];

// XX_cmp: sort by assending order
// XX_rcmp sort by descending order
bool score_cmp(student a, student b) {
if(a.score < b.score) return 1;
else return 0;
}

bool score_rcmp(student a, student b) {
if(a.score > b.score) return 1;
else return 0;
}

bool id_cmp(student a, student b) {
if(a.id < b.id) return 1;
else return 0;
}

bool id_rcmp(student a, student b) {
if(a.id > b.id) return 1;
else return 0;
}

bool name_cmp(student a, student b) {
if(a.name < b.name) return 1;
else return 0;
}

bool name_rcmp(student a, student b) {
if(a.name > b.name) return 1;
else return 0;
}

void PUT(int n) {
for(int i = 0; i < n; i++)
cout << s[i].id << ' ' <<  s[i].name << ' ' << s[i].score << endl;
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> s[i].id >> s[i].name >> s[i].score;
sort(s, s + n, name_rcmp); // an example of sorting name by descending order
PUT(n);
fclose(stdin);
fclose(stdout);
return 0;
}

点赞 打赏 评论