简体   繁体   English

我应该如何在此类的地图中重载“<”?

[英]How should I overload '<' in a map for this class?

I have the class tranzitie and a map<int, map<tranzitie, int>> .我有tranzitie类和map<int, map<tranzitie, int>> How should I overload the < operator for tranzitie in order for the map to work properly?我应该如何为tranzitie重载<运算符以使地图正常工作? It contains two chars and one string.它包含两个字符和一个字符串。 I tried, but find() would't work well, considering values equal even though they weren't (in my perspective).我试过,但 find() 效果不佳,考虑到值相等,即使它们不是(在我看来)。

class tranzitie{
public:
    char litera;
    char top;
    string newst;

    bool operator==(const tranzitie& x);
    tranzitie& operator=(const tranzitie& x);
    tranzitie (const tranzitie& x);
    tranzitie(){};
    inline bool operator< (const tranzitie& rhs) const;
};

Prefer implement operator< as a free function instead of a member function.更喜欢实现operator<作为自由函数而不是成员函数。 If you need to access the private members inside the operator< function you should make the operator< function a friend.如果您需要访问operator<函数内的私有成员,您应该让operator<函数成为朋友。 In your case it is not needed as the members of tranzitie are public.在您的情况下,不需要它,因为tranzitie的成员是公开的。

The easiest pattern to memorize is probably this:最容易记住的模式可能是这样的:

bool operator<(const tranzitie& lhs, const tranzitie& rhs) {
  if (lhs.litera < rhs.litera) return true;
  if (rhs.litera < lhs.litera) return false;
  if (lhs.top < rhs.top) return true;
  if (rhs.top < lhs.top) return false;
  return lhs.newst < rhs.newst;
}

The best pattern to memorize is probably this:最好记住的模式可能是这样的:

bool operator<(const tranzitie& lhs, const tranzitie& rhs) {
  return
    std::tie(lhs.litera, lhs.top, lhs.newst) <
    std::tie(rhs.litera, rhs.top, rhs.newst);
}

You should compare all your data members:您应该比较所有数据成员:

 bool operator< (const tranzitie& rhs) const {
     if( litera == rhs.litera ) {
        if( top == rhs.top ) {
            return newst < rhs.newst;
        }
        return top < rhs.top;
     }
     return litera < rhs.litera;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM