开发者

Comparing structs in C++

开发者 https://www.devze.com 2023-01-01 00:08 出处:网络
So in C++ There\'s a lot of times where you need to make an \"index\" class. For example: class GameID{

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 comp开发者_开发技巧arison just comes with it. Is there any other way to get that automatic operator comparison without having to use std::pair<> ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消