【问题标题】:why does the equivalent condition necessary?为什么等价条件是必要的?
【发布时间】:2020-08-13 07:20:49
【问题描述】:

我对来自C++ standard library 的代码有疑问。我的问题是 !(p2.lastname() < p1.lastname()) 似乎没有必要,因为我认为条件代表姓氏在 p1 和 p2 中等效。如果我删除了条件,代码似乎可以正常工作。我看到了这个严格的弱排序。我阅读了相关文章,但我并没有完全理解这个概念。你能解释一下为什么需要这个条件吗?

class Person {
public:
  string firstname() const;
  string lastname() const;
};

class PersonSortCriterion {
public:
  bool operator() (const Person& p1, const Person& p2) const {
    // 1) Compare the lastnames.
    // 2) If the lastnames are equivalent, compare the firstnames.
    return p1.lastname() < p2.lastname() ||
       (!(p2.lastname() < p1.lastname()) &&
          p1.firstname() < p2.firstname());
  }
};

【问题讨论】:

  • 这里的equivalent 是什么意思?
  • return std::tuple{lhs.lastname, lhs.firstname()} &lt; std::tuple{rhs.lastname, rhs.firstname()}; 更容易理解 IMO(可能使用 as_tuple 方法分解),并避免破坏严格的弱排序。
  • @Jinchul 你|| 的后半部分是错误的。您需要使用== 而不是!&lt;,这与&gt;= 相同,这不是您在这种情况下想要的。 return (p1.lastname() &lt; p2.lastname()) || ((p1.lastname() == p2.lastname()) &amp;&amp; (p1.firstname() &lt; p2.firstname())); 或者,使用一个元组,就像 Jarod 展示的那样,因为它已经为你实现了 &lt;

标签: c++ strict-weak-ordering


【解决方案1】:

所以我认为你是说以下是可以的

return p1.lastname() < p2.lastname() ||
      p1.firstname() < p2.firstname());

但这是不正确的。考虑两个人“Andy Zerkis”和“Zebedee Archer”。使用上面的代码 AZ

如果您不熟悉严格的弱排序,它似乎会让人感到困惑,但实际上它只是说明了您对任何排序标准的期望。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 2023-03-25
    • 2015-12-22
    • 2014-10-28
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多