views:

104

answers:

2

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<> ?

+6  A: 

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.

James McNellis
+1  A: 

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.

shuttle87
All the standard functions algorithms define things in terms of operator<. If you define operator < and operator == all the other relational operators can be defined via these two and as such the standard libs provide the extra functionality to do so automatically.
Martin York
@Martin, good point. Edited to include this info.
shuttle87