kamziro
kamziro

Reputation: 8140

Comparing structs in C++

So in C++ There's a lot of times where you need to make an "index" class. For example:

class GameID{
   public:
      string name;
      int regionid;
      int gameid;
      bool operator<(const GameID& rhs) const;
}

Now, if we were to represent GameID as pair<string, pair<int, int> >, the operator comparison just comes with it. Is there any other way to get that automatic operator comparison without having to use std::pair<> ?

Upvotes: 0

Views: 514

Answers (2)

shuttle87
shuttle87

Reputation: 15934

If you want to compare the elements in the struct or class that you are defining here you will need to define your own operator overload for ">" or "<" depending on the way you want to compare them.

For example you could do something like this:

class GameID{
   public:
      string name;
      int regionid;
      int gameid;


      inline bool operator > (Game_ID first_game, Game_ID second_game)
      {
          return (first_game.gameID() > second_game.gameID());
      }

}

As pointed out in the comment by Martin, the standard functions algorithms define things in terms of operator<. So if you define operator < and operator == the other relational operators can be defined via these and as such the standard libs provide the extra functionality to do so automatically.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355039

You get an operator< when you use std::pair because std::pair implements an operator< overload. It works when you use std::string as one of the types in the pair because std::string also overloads operator<.

If you want to be able to compare objects of your own class type, you need to overload operator< as well.

Upvotes: 6

Related Questions