Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing other comparison operators in terms of operator< in one call

Tags:

c++

comparison

I've seen that, if you have operator<, you can implement, say, operator>= as !(a < b). However, when I went to the C++ Committee in Bristol, they said that you can implement all the comparison operators this way. Particularly, when considering types which have non-trivial comparison operators (consider an arbitrarily long string, especially if this is Unicode), this can be done with only one call to operator<. I cannot conceive of how this could be done.

How can I implement operator> and operator<= with just one call to operator< and none to the other comparison operators?

like image 788
Puppy Avatar asked Aug 17 '13 14:08

Puppy


People also ask

What is the use of comparison operators give examples of comparison operators?

Comparison operators allow us to assert the equality of a statement with JavaScript. For example, we can assert whether two values or expressions are equal with === , or, whether one value is greater than another with > .

What are the operators used for comparing of values called?

The equality operator uses to compare two values. The user can check the comparison using the equality operator. Double equal symbol is the equality operator. Using " ==", the equality operator one can compare or check boolean, string, numeral, etc.


1 Answers

  • a > b == b < a
  • a <= b == !(b < a)
  • a >= b == !(a < b)

It's even possible to implement equality in terms of less than (Kind of abusing my meta-syntax here):

  • (a == b) == (!(a < b) && !(b < a))
  • (a != b) == (a < b || b < a)

Although I wouldn't suggest doing so in practice, since it requires two comparisons and can generally be implemented more efficiently directly.

like image 71
Casey Avatar answered Nov 06 '22 04:11

Casey