opCmp()

Learn how to use opCmp() for comparisons in sorting in this lesson.

We'll cover the following...

opCmp() for sorting

Sort operators determine the sort orders of objects. All of the ordering operators, <, <=, >, and >=, are covered by the opCmp() member function.

For structs, the parameter of opCmp can be defined as in. However, as with opEquals, it is more efficient to define opCmp as a template that takes auto ref const:

int opCmp()(auto ref const TimeOfDay rhs) const {
    // ...
}

To reduce confusion, opEquals and opCmp must work consistently. For every two objects that opEquals returns true, opCmp must return zero.

Let’s assume that one of these four operators is used as in the following code:

 ...