# Mathematics behind Comparison #1: Equality and Equivalence Relations

In order to sort a collection of elements you need to provide a sorting predicate that determines when one element is less than the other. This predicate must “induce a strict total ordering on the equivalence classes” according to cppreference. Wait, what?

The upcoming C++ spaceship operator implements a three way comparison,
i.e. it is a single function that can return the results of `<`

, `==`

and `>`

combined.
But related to it are terms like “strong equality” and “weak ordering” which are somewhat confusing if you don’t have the mathematical background.

So let’s untangle it: This series will explain both the mathematics behind equality and ordering, as well as give concrete guidelines for implementing the comparison operators and the spaceship operator.

This part covers equality and equivalence relations. What does it mean for two objects to be equal? What are the mathematical properties and C++ semantics it needs to fulfill? How do I implement proper equality comparison in C++?

In the following parts we’ll look at ordering relations, the new three way comparison and algorithms like sorting and searching on various orderings.

» read more »