如何为结构/类字符串实现比较操作员

How to implement a compare-operator for a struct/class of strings?

本文关键字:字符串 实现 比较 操作员 结构      更新时间:2023-10-16

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