Sorting a String Array Alphabetically C++

Buffalo282 picture Buffalo282 · Apr 7, 2017 · Viewed 27.5k times · Source

I'm trying to write a program that is given the following structures:

struct aPlayer {
  string name;  // name of player
  int wins;     // number of wins player has
};

struct aCompetition {
  string  name;                 // name of the match
  int     numPlayers;           // number of players in the club
  aPlayer player[10];           // list of players in this club
};

From there I want to write a function that will sort the players by name alphabetically. The function declaration would be as follows:

    void sortByName(aCompetition & c){}

Note: I would like to do this by only using for loops, while loops, and if statement(s). The only way I could think to compare the two strings would be to compare their ASCII values. I'm not sure how to do that so any input will be greatly appreciated. Thanks!

Answer

ephemient picture ephemient · Apr 7, 2017

Sorting is provided by the standard library, on types with an operator<, or other types if given that comparator. You can build one off of string::operator< which performs lexical comparison.

#include <algorithm>
void sortByName(aCompetition& c) {
    sort(&c.player[0], &c.player[c.numPlayers],
            [](const aPlayer& a, const aPlayer& b) {return a.name < b.name;});
}

If you don't have C++11 lambdas then you'd use a functor.

struct compareAPlayerByName {
    boolean operator()(const aPlayer& a, const aPlayer& b) {
        return a.name < b.name;
    }
};
void sortByName(aCompetition& c) {
    sort(&c.player[0], &c.player[c.numPlayers], compareAPlayerByName());
}