python - std::unordered_set 的 C++ 比较运算符
问题描述
这篇文章提出了一个问题,即>
C <
++ 中无序容器的比较运算符不存在。从回复来看,拥有这些似乎毫无意义。
但是,我检查了 Python,发现该set
类型支持子集和超集操作。Pythonset
是一个哈希表。我们可以轻松做到:
{'1', '6', 't', 'j'} > {'1', '6', 'j'} # superset
True
{'1', '6', 'j', 't'} < {'1', '6', 'j'} # subset
False
如何在 C++ 中为哈希表()实现比较运算符std::unordered_set
?还是我们必须坚持std::set
平等以外的任何比较?
解决方案
Python 的集合基于子集关系具有部分顺序,而不是全顺序。例如,既不是{ 1, 2, 3 } < { 2, 3, 4 }
也不{ 1, 2, 3 } > { 2, 3, 4 }
是真的,而是{ 1, 2, 3 } == { 2, 3, 4 }
假的。
你可以写一个<
这样的行为,但正如评论中所指出的,你不能把它放进去namespace std
,所以在某些情况下它不会被发现。
我建议改为制作免费功能
template<typename UnorderedContainer>
bool is_proper_subset(const UnorderedContainer & lhs, const UnorderedContainer & rhs);
您还可以对<=
,>
和>=
(分别)进行变体
template<typename UnorderedContainer>
bool is_subset(const UnorderedContainer & lhs, const UnorderedContainer & rhs);
template<typename UnorderedContainer>
bool is_proper_superset(const UnorderedContainer & lhs, const UnorderedContainer & rhs);
template<typename UnorderedContainer>
bool is_superset(const UnorderedContainer & lhs, const UnorderedContainer & rhs);
推荐阅读
- python - Python Pandas 对多个条件求和
- c# - C# IoC 项目结构标准
- azure - Azure Function Java:绑定类型 blobTrigger 未注册
- c# - 无法使用公共 IP 连接到 EC2 上的 MongoDB
- php - Twig 不在项目的 app/Resources/views 文件夹中查找模板
- excel - 将行复制到取决于条件的位置
- json - 状态页 io json 解析
- java - 文本分类,如何将文本字符串转换为向量表示
- python - 如何修复 TensorFlow 线性回归在 MSE 中没有变化?
- javascript - 如何将数组插入另一个数组