如何为结构/类字符串实现比较操作员
How to implement a compare-operator for a struct/class of strings?
我有一个代表分解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
相关文章:
- 我如何在C++像在 Python 中一样实现 f 字符串?
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- "in-situ without memory allocation" 字符串的愚蠢实现意味着什么?
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- 如何实现通用比较?(用于数字和字符串)
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 实现一个函数,该函数将字符串作为输入并返回一个新字符串,辅音字母不替换为 "!"
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- C++ 中字符串实现的二叉搜索树
- 如何为结构/类字符串实现比较操作员
- C 字符串实现
- C 字符串实现错误
- C++类字符串实现
- 自定义字符串实现中 c_str() 函数中的恒常性问题
- 自定义字符串实现,运算符 + 过载内存分配问题
- C++11 constexpr 字符串实现
- c++中的简单字符串实现
- STLPort 的字符串实现是否使用引用计数?
- 字符串实现的排列问题
- 字符串实现和表达式模板