What's the difference between! (x <y) and x> = y in C ++?

After going through EASTL, I came across a strange line of code. The following link shows the file with the line number of interest at step 1870.

https://github.com/paulhodge/EASTL/blob/master/include/EASTL/algorithm.h

The code on this line is if(!(value < *i)) . The commentary says that "we always express comparisons of values ​​in terms of" lt == or == "without any explanation as to why this is so. There are also several other areas where the same comment is placed, but without which any explanation.

Is there any use to writing such a comparison (maybe some context that I skip)? If not, why did the author of EASTL intentionally write it that way and even take care of it? Is the only reason here is the only reason?

+6
source share
4 answers

This means that you need to provide < and == for container value types. It also means that you reduce the amount of volatility for these types (since all algorithms use !(a<b) to denote a>=b and !(a==b) for a!=b ); otherwise, you could >= and != return inconsistent results.

+11
source

In C ++, you can overload the < operator so that it behaves differently than the opposite >= , so they are not guaranteed to be equivalent.

In addition, in any floating-point implementation, IEEE NaN < NaN is false, but also has the value NaN >= NaN , therefore !(NaN < NaN) true even if NaN >= NaN is false.

+8
source

I see at least one difference. If one of the numbers was QNAN (floating point 0/0), then! (A <b) would always return TRUE if any of a or b was a QNAN, whereas it would always return false for a> = b

+1
source

Using only the smaller operator, you can simulate all other comparison operators. This makes it more consistent and allows you to use a single template parameter when you need to parameterize the comparison. Standard sorted containers and algorithms use std::less<T> as the default default comparator, for example.

 operation equivalent x < yx < y x > yy < x x <= y !(y < x) x >= y !(x < y) x == y !(x < y) && !(y < x) x != y (x < y) || (y < x) 

For operations where ordering is not important, it’s easier and more efficient to use the == operator.

+1
source

Source: https://habr.com/ru/post/905162/


All Articles