成绩排序(HJ68)

一:解题思路

这道题目考察了稳定排序。

二:完整代码示例 (C++版和Java版)

C++代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct student
{
    string name;
    int score;
};

bool campare_min2max(const student& s1, const student& s2)
{
    return s1.score < s2.score;
}

bool campare_max2min(const student& s1, const student& s2)
{
    return s1.score > s2.score;
}

int main()
{    
    int n = 0;
    bool min2max =true;

    while (cin >> n >> min2max)
    {
        vector<student> stu(n);

        for (int i = 0; i < n; i++)
        {
            cin >> stu[i].name >> stu[i].score;
        }

        if (min2max)
            stable_sort(stu.begin(), stu.end(),campare_min2max);
        else
            stable_sort(stu.begin(),stu.end(),campare_max2min);

        for (int i = 0; i < n; i++)
            cout << stu[i].name << " " << stu[i].score << endl;

    }

    return 0;
}

 

posted @ 2020-08-02 11:54  repinkply  阅读(368)  评论(0)    收藏  举报