2016-12-26 78 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这个成员的原型是怎么样的? –