怎么将文件读取后按照学号姓名成绩进行3次不同的升序和降序,并输出到txt中。
求代码 求大神
s1109853011,JackieChan,CS001,85
s0907451244,FrankPapadias,MA002,65
s0308893477,MirandaLambert,HM467,35
s4045128481,SophiaPam,CM604,75
s0812340023,PhilipsChiu,CS001,71

求教数据结构排序问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报