这两个比较表达式是否相同? [英] Are these two comparison expressions identical?
问题描述
在另一个问题中似乎有一些意见分歧关于这两个函数是否具有相同的逻辑:
There seems to be some disagreement in another question about whether these two functions have identical logic:
bool operator<(const screenPoint& left, const screenPoint& right){
if (left.x < right.x) return true;
else return left.y < right.y;
}
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x < right.x || left.y < right.y;
}
我盯着这些看了一会儿,行为不同。在两者中,如果 left.x< right.x
,它们都返回 true
。如果不是,那么它们都返回 left.y< right.y
。对吗?
I have stared at these for quite a while and I cannot see how they would behave differently. In both, if left.x < right.x
, they both return true
. If not, then they both return the result of left.y < right.y
. Right?
如果没有,可以请详细说明。
If not, can someone please elaborate.
与 std :: tie
中的词典顺序的实现是否相同?
Also, it was suggested that the first of these is identical to the implementation of lexographical ordering in std::tie
, is that true?
推荐答案
这两个是相同的(如果你修复了第一个 if
中缺少的括号),但它们没有实现严格的弱排序,所以您可能不想使用它们(在标准有序容器和算法中使用它们是无效的)。
The two are identical to each other (if you fix the missing parenthesis in the first if
), but they do not implement a strict weak ordering, so you probably don't want to use them (it would be invalid to use them in standard ordered containers and algorithms).
证明:考虑a = 1,3)b =(2,2)。然后, b和b <一个。 (不对称属性违反)
Proof: Consider the original relation for a=(1,3) b=(2,2). Then a < b and b < a. (asymmetric property violated)
正确的词典顺序如下:
bool operator<(const screenPoint& left, const screenPoint& right){
if (left.x < right.x)
return true;
if (left.x > right.x)
return false;
return left.y < right.y;
}
如果您的会员只有< code>运算符而不是
>
运算符,替换 left.x> right.x
由!(right.x< left.x)
。这是如何通过 std :: pair
和 std :: tuple
(由 std :: tie
)。
If your members have only a <
operator and not a >
operator, replace left.x > right.x
by !(right.x < left.x)
. This is how lexicographical comparison is implemented by std::pair
and std::tuple
(which is returned by std::tie
).
这篇关于这两个比较表达式是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!