Search code examples
c++stringoperator-overloadingalphabet

C++ - Alphabetizing Strings


I am currently reading information from an input file. Of that information, there is a name. All the information is read into a struct. There is an array of these structs.

I need to alphabetize the structs by the last name, using a Binary Search Tree.

Do I need to write an operator overload function for ==, <, and >. If so can someone help me get started on that?


Solution

  • Operator overloads work just like functions or methods. They get a return type and arguments in just the same way. For instance, a binary operator (like <) would be a member function with one argument or a free function with two, one each for each side of the operator. the only thing that's different is instead of having an identifier function name, they use a special syntax, the keyword operator followed by the operator being overloaded. So if we wanted to have a comparable type, we could do it this way:

    class MyUserType
    {
      private:
        std::string sort_significant;
        std::string sort_insignificant;
      public:
        bool operator<(const MyUserType &) const;
    };
    
    bool MyUserType::operator<(const MyUserType & other) const
    {
       return sort_significant < other.sort_significant;
    }