Search code examples
c++functioncomparealphabetical

c++ how to determine whether one word is before another in the alphabet


I'm using the sort() function in C++ to sort a vector of objects of type 'Game', which I defined myself. To do this, I am manually writing a function that will act in place of the operator<, and which will be passed as the third parameter to the sort() function. First, I compare based on scores. Then, if scores are tied, I compare based on team name.

What I need is a function alphabetical(string s1, string s2), that will return true if s1 would come before s2 in the dictionary. For example:

alphabetical("aardvark", "apple"); //true
alphabetical("balloon", "zebra"); //true
alphabetical("zebra", "apple"); //false

I also want it to return false if the strings are identical. Is there something in a library that I could use? Or, how would I write the function? I hope I'm coming across clearly.


Solution

  • std::string implements a lexicographical less-than comparison operator itself, meaning that stringA < stringB should usually do what you want. If you create a std::list<std::string> words, sorting alphabetically will be as simple as words.sort();

    Your custom Game class could have its less-than comparison operator implemented simply as:

    return (score < rhs.score) || (score == rhs.score && team < rhs.team)
    

    It is worth noting that lexicographical sorting will not always be what a human would expect. Jeff Atwood goes into a discussion of so-called "natural sort order" versus lexicographical sort order in this post. His post also provides resources from which you will be able to find algorithms if such sorting is necessary to you.