2013-03-13 19 views
0

我有時想使用包含多個值的map和set中的鍵。我不太在乎速度。有沒有簡單或一般的方法來編寫運算符<來比較具有多個值的結構?我自己想出了以下內容,但它很乏味,特別是隨着價值數量的增加。謝謝。如何實現operator <用於STL數據結構中使用的任意結構?

struct Properties 
{ 
    Properties() {} 

    Properties 
     (const string& data1 
     , const string& data2 
     , const string& data3 
     ) 
     : data1(data1) 
     , data2(data2) 
     , data3(data3) 
    {} 

    string data1; 
    string data2; 
    string data3; 

    bool operator < (const Properties& other) const 
    { 
     if (this->data1 == other.data1) 
     { 
      if (this->data2 == other.data2) 
      { 
       if (this->data3 == other.data3) 
       { 
        return false; 
       } 
       else 
       { 
        return this->data3 < other.data3; 
       } 
      } 
      else 
      { 
       return this->data2 < other.data2; 
      } 
     } 
     else 
     { 
      return this->data1 < other.data1; 
     } 
    } 
}; 

回答

0

您可能會嘗試將它們轉換爲元組,並將它們進行比較。這將取代你的Properties類。

4

您可以使用std::tie此:

#include <tuple> 

bool operator<(Properties S& rhs) const 
{ 
    return std::tie(data1, data2, data3) < std::tie(rhs.data1, rhs.data2, rhs.data3); 
} 

這工作,獨立的類型dataN的(條件是它們具有operator<)。

1

它確實比較單調乏味。

當然,如果你存儲在陣列數據[假設所有的數據是相同類型的],你可以使用一個循環:

const int numstrings = 3; 
string data[3]; 

... 

bool operator < (const Properties& other) const 
{ 
    for(int i = 0; i < 3; i++) 
    { 
     if (data[i] != other.data[i]) 
     { 
      return data[i] < other.data[i]; 
     } 
    } 
} 

當然,你也可以縮短現有的代碼位:

bool operator < (const Properties& other) const 
{ 
    if (this->data1 != other.data1) 
    { 
     return this->data1 < other.data1; 
    } 
    if (this->data2 != other.data2) 
    { 
     return this->data2 < other.data2; 
    } 
    return this->data3 < other.data3; 
} 
0

你能做到這一點在這樣一個更平坦的方式:

bool operator < (const Properties& other) const 
{ 
    if (this->data1 < other.data1) 
     return true; 
    if (other.data1 < this->data1) 
     return false; 

    if (this->data2 < other.data2) 
     return true; 
    if (other.data2 < this->data2) 
     return false; 

    return this->data3 < other.data3; 
} 
0

傳統的方式做THI s是如下

bool operator<(Properties const& lhs, Properties const& rhs) const 
{ 
    return (lhs.data1 < rhs.data1) 
      || (!(rhs.data1 < lhs.data1) && lhs.data2 < rhs.data2) 
      || (!(rhs.data1 < lhs.data1) && !(rhs.data2 < lhs.data2) && lhs.data3 < rhs.data3; 
} 

這有工作了所有類型的operator<定義的,而不是依靠operator==的優勢。

+0

雖然它有不工作的缺點。例如,{3,3,1}'會比較小於{2,2,2}',這可能不是OP所期望的。 – molbdnilo 2013-03-13 13:00:18

+0

@molbdnilo固定。 – 2013-03-13 13:27:43