【发布时间】: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()} < std::tuple{rhs.lastname, rhs.firstname()};更容易理解 IMO(可能使用as_tuple方法分解),并避免破坏严格的弱排序。 -
@Jinchul 你
||的后半部分是错误的。您需要使用==而不是!<,这与>=相同,这不是您在这种情况下想要的。return (p1.lastname() < p2.lastname()) || ((p1.lastname() == p2.lastname()) && (p1.firstname() < p2.firstname()));或者,使用一个元组,就像 Jarod 展示的那样,因为它已经为你实现了<。