-2

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
Somit
  • 303
  • 2
  • 10

1 Answers1

1

Assuming that you are using a compare function to feed into std::sort method, your function should return a bool. Starting the if block with == and returning the difference between scores without an abs operator made the logic a bit confusing.

Basically, when you return int type and it is not equal to 0, it is treated as true. Therefore, your else block would only return true even if q.score > p.score or p.score > q.score.

There are many ways of lexicographical comparison for strings: Some of them are discussed here.

bool compare(Player p, Player q){
    if(p.score == q.score){
        return p.name > q.name;
    }
    else{
        return p.score > q.score;
    }
}
Serkan Pekçetin
  • 658
  • 7
  • 14