[HackerRank]Sorting Comparator

Sorting: Comparator

这道题让我们将分数从大到小排序,遇到分数相同时候,按名字字母从小到大排序。

一开始我还想着要手写一个快速排序,后来发现这道题其实是一个教学,教我们字母自定义比较函数,并用于STL的函数中。

这样一来思路就很清晰了,比较函数很简单,如果分数高,或者分数相同但字母小,则返回true

bool comp(Player& a, Player& b){
    return (a.score>b.score || (a.score==b.score && a.name < b.name));
}

再完成功能函数,也很简单清晰:

vector comparator(vector players) {
    sort(players.begin(),players.end(),comp);
    return players;
}

值得一提的是,比较函数comp一定要放在功能函数comparator的前面,否则编译会出错。

完整代码如下:

#include 
#include 
#include 
#include 
#include 

using namespace std;

struct Player {
    string name;
    int score;
};

/******************************************************************************/

bool comp(Player& a, Player& b){
    return (a.score>b.score || (a.score==b.score && a.name < b.name));
}

vector comparator(vector players) {
    sort(players.begin(),players.end(),comp);
    return players;
}

/******************************************************************************/

int main() {

    int n;
    cin >> n;
    vector< Player > players;
    string name;
    int score;
    for(int i = 0; i < n; i++){
        cin >> name >> score;
        Player p1;
        p1.name = name, p1.score = score;
        players.push_back(p1);
    }

    vector answer = comparator(players);
    for(int i = 0; i < answer.size(); i++) {
        cout << answer[i].name << " " << answer[i].score << endl;
    }
    return 0;
}

你可能感兴趣的:(Coding,C++)