2016-11-14 51 views
0

std::map(函數省略)中,實現'<'運算符使用以下簡單類作爲鍵的正確方法是什麼?實現'<'運算符

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 
} 
+0

不是欺騙,但一個很好的參考:HTTP:// stackoverflow.com/questions/4421706/operator-overloading – NathanOliver

+0

你有一個名爲'id'的字段。它的名字暗示它是獨一無二的。是嗎?如果是這樣,你可以利用這個事實。 – hvd

+0

沒有「正確的」方法。只要它滿足*嚴格的弱排序*,它就取決於你。 – juanchopanza

回答

4

您可以使用std::tie

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 

    bool operator<(const Person& r) const 
    { 
     return std::tie(valid, name, id) < std::tie(r.valid, r.name, r.id); 
    } 
} 

說明:

std::tie(xs...)創建於通過xs...參數引用的std::tupleComparison between two std::tuple instances作品按字典順序排列比較元素,從而爲您的類型提供排序。

更多信息here on cppsamplesin this question

+0

哈哈!英雄所見略同。 –

+2

@RichardHodges:現在讓我們爭取**會員功能** vs **免費功能**! –

+0

更好地解釋如何/爲什麼'領帶'是要走的路/它在做什麼。 – NathanOliver

2
#include <string> 
#include <tuple> 

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 
}; 

bool operator<(const Person& l, const Person& r) 
{ 
    return std::tie(l.valid, l.name, l.id) < std::tie(r.valid, r.name, r.id); 
} 
4

您可以使用std::tie其他答案建議。如果你想清楚地看到邏輯在自己的功能或沒有訪問C++編譯器11,可以實現它:

class Person 
{ 
    public: 
     bool valid = false; 
     std::string name = ""; 
     std::string id = ""; 

     bool operator<(Person const& rhs) const 
     { 
     if (this->valid != rhs.valid) 
     { 
      return (this->valid < rhs.valid); 
     } 
     if (this->name != rhs.name) 
     { 
      return (this->name < rhs.name); 
     } 
     return (this->id < rhs.id); 
     } 
}; 
+0

如果是我,我會做到這一點,因此所有無效對象都是等效的,而不依賴於其他成員。這是你無法用'std :: tie'完成的事情。 –

+1

應該指出的是,'std :: tuple'使用等同性,而這個實現使用相等性。這些類型是一樣的,但不是一般的。 – StoryTeller