c++ less operator overload, which way to use?

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

For example: in a C++ header file, if I defined a struct Record and I would like to use it for possible sorting so that I want to overload the less operator. Here are three ways I noticed in various code. I roughly noticed that: if I'm going to put Record into a std::set, map, priority_queue, … containers, the version 2 works (probably version 3 as well); if I'm going to save Record into a vector<Record> v and then call make_heap(v.begin(), v.end()) etc.. then only version 1 works.

  struct Record   {       char c;       int num;        //version 1       bool operator <(const Record& rhs)       {          return this->num>rhs.num;       }        //version 2       friend bool operator <(const Record& lhs, const Record& rhs) //friend claim has to be here       {          return lhs->num>rhs->num;       }   }; 

in the same header file for example:

      //version 3       inline bool operator <(const Record& lhs, const Record& rhs)       {          return lhs->num>rhs->num;       } 

Basically, I would like to throw the questions here to see if someone could come up with some summary what's the differences among these three methods and what are the right places for each version?

回答1:

They are essentially the same, other than the first being non-const and allowing you to modify itself.

I prefer the second for 2 reasons:

  1. It doesn't have to be a friend.
  2. lhs does not have to be a Record


回答2:

The best way to define the less operator is:

struct Record{     (...)     const bool operator < ( const Record &r ) const{         return ( num < r.num );     } }; 


回答3:

Favor in-class unless it cannot be in-class because first argument is the wrong type.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!