如何为struct / class of strings实现compare-operator?

时间:2016-12-26 07:26:59

标签: c++ c++11 operator-overloading

我有一个代表分解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;
}

1 个答案:

答案 0 :(得分: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