Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between equivalent and equal for c++20 three way comparison operator?

Tags:

c++

c++20

In c++20 the new three way comparison operator <=> (spaceship operator) is introduced and it can result into four values given below :

  1. std::strong_ordering::less
  2. std::strong_ordering::equivalent
  3. std::strong_ordering::equal
  4. std::strong_ordering::greater

However when I run below code snippet it appears that both equal and equivalent are one and some thing, so I want to know what is the difference between them and in what scenario we should prefer one over another.

#include <iostream>
#include <compare>
int main()
{
    std::strong_ordering res = (2<=>2);
    if(res == std::strong_ordering::equivalent)
    {
        std::cout<<"Equivalent...."<<std::endl;
    }
    if(res == std::strong_ordering::equal)
    {
        std::cout<<"Equal"<<std::endl;
    }
    return 0;
}

O/P :

Equivalent....

Equal

like image 393
PapaDiHatti Avatar asked Sep 12 '25 07:09

PapaDiHatti


1 Answers

They are the same thing, both numerically and conceptually. If a comparison generates strong ordering between the items being compared, equivalence and equality are the same.

The reason there are two words for it is because this is not the same for other kinds of ordering. Weak and partial don't have equality at all; they only provide equivalence.

Equivalence means that two objects can compare equal. Equality implies something stronger; if they compare equal, one can be substituted for the other in any const usage:

the property that f(a) == f(b) is true whenever a == b is true, where f denotes a function that reads only comparison-salient state that is accessible via the argument's public const members.

If a type's comparison permits equality (which is a requirement of strong ordering), then it also permits equivalence. So for a strongly ordered comparison, they are the same.

like image 91
Nicol Bolas Avatar answered Sep 13 '25 22:09

Nicol Bolas