2016-12-26 48 views
-1

我有一個代表分解URL的類。如何爲結構/字符串類實現比較運算符?

class URL 
{ 
    std::string proto_; 
    std::string host_; 
    /* other fields */ 
}; 

(例如,proto_可以是HTTP,HTTPS,LDAP; host_可以是localhost:1234,google.com)。

要比較的真實有意義的值當然是組成的URL。但構建它是昂貴的,我想使用這個類的鑰匙類型爲std::map

如何以有效的方式爲此課程實施operator<()?如何結合不同對象的比較,這些對象在邏輯上構成了一個整體?

我試過使用std::tie但結果並不如我預期的那樣。

按照意見

這裏要求是目前我在做什麼(工作如預期):

friend bool operator<(const uri &l, const uri &r) 
{ 
    std::string ls = l.proto_ + l.host_; 
    std::string rs = r.proto_ + r.host_; 
    return ls < rs; 
} 
+0

按字母順序排列。比較第一個字段。如果相等,請比較第二個字段等。 –

+0

請發佈您嘗試過的內容,期望看到的輸出內容以及實際輸出內容。 –

+2

使用'std :: tie'但沒有錯誤。 – juanchopanza

回答

3
class URL 
{ 
    std::string proto_; 
    std::string host_; 
    /* other fields */ 
public: 
    bool operator<(const URL& o) const { 
     if (proto_ != o.proto_) 
      return proto_ < o.proto_; 
     if (host_ != o.host_) 
      return host_ < o.host_; 
     return false; 
    } 
}; 

比較功能應滿足Compare概念。

這也非常實用,太:

bool operator<(const URL& o) const { 
     return std::tie(proto_, host_) < std::tie(o.proto_, o.host_); 
    } 

或:

class URL 
{ 
    std::string proto_; 
    std::string host_; 
    /* other fields */ 
public: 
    bool operator<(const URL& o) const { 
     return tie() < o.tie(); 
    } 
    /* std::tuple<std::string&, std::string&> */ 
    auto tie() { 
     return std::tie(proto_, host_); 
    } 
    auto tie() const { 
     return std::tie(proto_, host_); 
    } 
}; 

與C++ 11和沒有C++ 14,你需要這樣的:

auto tie() -> decltype(std::tie(proto_, host_)){ 
    return std::tie(proto_, host_); 
} 
auto tie() const -> decltype(std::tie(proto_, host_)) { 
    return std::tie(proto_, host_); 
} 

demo

+2

不妨將'std :: tie'用於更短,更少出錯的代碼。 – juanchopanza

+2

我建議在成員函數中包裝'std :: tie'調用,以避免重複自己。在添加新參數時,減少混淆參數順序的機會。 – StoryTeller

+0

@StoryTeller這個成員的原型是怎麼樣的? –