Friday, 21 October 2016

Comparator (CTCI)

Problem: Comparator
Given an array of  Player objects, write a comparator that sorts them in order of decreasing score; if  or more players have the same score, sort those players alphabetically by name.

struct Player {
    string name;
    int score;
}; 

bool compare(Player a, Player b)
{
    if(a.score != b.score) return a.score>b.score;
    return a.name<b.name;    
}

vector<Player> comparator(vector<Player> players) {
       sort(players.begin(), players.end(), compare);
       return players;
}

No comments:

Post a Comment