I have been trying to solve this problem for the past couple of days and I cannot figure out a solution to the way compare function should be coded. What i am trying to do is sort the scores in descending order and in case of same score sort them lexicographically according to their name.Below is the code and expected output and my output.
Code
#include<bits/stdc++.h>
using namespace std;
struct Player {
string name;
int score;
};
int compare(Player p,Player q)
{
if(p.score==q.score)
return p.name.compare(q.name);
else
return q.score-p.score;
}
vector<Player> comparator(vector<Player> players) {
sort(players.begin(),players.end(),compare);
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<Player > answer = comparator(players);
for(int i = 0; i < answer.size(); i++) {
cout << answer[i].name << " " << answer[i].score << endl;
}
return 0;
}
My output:
aleksa 150
aakansha 75
heraldo 50
david 100
amy 100
Correct Output
aleksa 150
amy 100
david 100
aakansha 75
heraldo 50