C++ 如何为字符串的结构/类实现比较运算符?

C++ 如何为字符串的结构/类实现比较运算符?,c++,c++11,operator-overloading,C++,C++11,Operator Overloading,我有一个表示分解URL的类 class URL { std::string proto_; std::string host_; /* other fields */ }; 例如,协议可以是http、https、ldap;主机可以是localhost:1234,google.com 要比较的真正有意义的值当然是合成的URL。但是构造它是昂贵的,我想使用这个类作为std::map的键类型 如何实现运算符 或: 按词典编纂。比较第一个字段。如果相等,请比较第二个字段等。请发

我有一个表示分解URL的类

class URL
{
    std::string proto_;
    std::string host_;
    /* other fields */
};
例如,协议可以是http、https、ldap;主机可以是localhost:1234,google.com

要比较的真正有意义的值当然是合成的URL。但是构造它是昂贵的,我想使用这个类作为std::map的键类型

如何实现运算符 或:


按词典编纂。比较第一个字段。如果相等,请比较第二个字段等。请发布您尝试过的内容、您期望看到的输出以及实际输出。使用std::tie,但不要有错误。最好使用std::tie来编写更短、更不容易出错的代码。我建议将std::tie调用包装到成员函数中,以避免重复。添加新成员时,很少有机会混淆参数顺序。@StoryTeller此成员的原型如何?@PatrickB。我只想用:
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;
}
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;
    }
};
    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_);
    }
};
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_);
}