weixin_43616382 2018-11-17 10:28 采纳率: 33.3%
浏览 440
已采纳

求教数据结构排序问题

怎么将文件读取后按照学号姓名成绩进行3次不同的升序和降序,并输出到txt中。
求代码 求大神
s1109853011,JackieChan,CS001,85
s0907451244,FrankPapadias,MA002,65
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;
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?