首页 > 解决方案 > 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平等以外的任何比较?

标签: pythonc++hashsetunordered

解决方案


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);

推荐阅读