【问题标题】:C++ Comparison operators for std::unordered_setstd::unordered_set 的 C++ 比较运算符
【发布时间】:2021-01-14 19:20:50
【问题描述】:

This 的帖子提出了一个问题,即 C++ 中无序容器的比较运算符不存在 >< ..。从回复来看,拥有这些似乎毫无意义。

但是,我检查了 Python 并看到 set 类型支持子集和超集操作。 Python set 是一个哈希表。我们可以轻松做到:

{'1', '6',  't', 'j'} > {'1', '6', 'j'}   # superset
True
{'1', '6', 'j', 't'} < {'1', '6', 'j'}    # subset
False

如何在 C++ 中为哈希表 (std::unordered_set) 实现比较运算符?或者我们必须坚持std::set 才能进行除平等之外的任何比较?

【问题讨论】:

  • 您仍然可以根据需要定义自己的自定义关系。
  • 您不能为std 类型添加运算符重载,因为ADL 将找不到它们(并且您不能向命名空间std 添加任何内容)。你可以实现一个函数或函数对象。
  • std::set uses lexicographic comparison。您可以考虑使用std::lexicographical_compare` 来实现与std::unordered_set 相同的效果。

标签: python c++ hash set unordered


【解决方案1】:

Python 的集合基于子集关系具有偏序,而不是全序。例如。 { 1, 2, 3 } &lt; { 2, 3, 4 }{ 1, 2, 3 } &gt; { 2, 3, 4 } 都不是真的,但{ 1, 2, 3 } == { 2, 3, 4 } 是假的。

您可以编写一个具有类似行为的&lt;,但正如 cmets 中所述,您不能将其放入 namespace std,因此在某些情况下找不到它。

我建议改为创建一个免费功能

template<typename UnorderedContainer>
bool is_proper_subset(const UnorderedContainer & lhs, const UnorderedContainer & rhs);

您还可以对&lt;=&gt;&gt;=(分别)进行更改

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2023-03-03
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多