Description
There are lots of builtin containers in C++, via which we can easily and efficiently achieve what we want. However, sometimes the sorting ability of them is relatively limited and as a result, we have to come up with the custom comparer
to redefine the sorting feature. I will try to discuss most of them encountering different situations.
Strict Weak Ordering
Almost all functions/containers (except for example priority_queue) require the ordering to satisfy the standard mathematical definition of a strict weak ordering, or else the behavior of the functions/containers will be undefined.
Let f(x, y) be a comparison function. f is in strict weak ordering if it satisfies three invariants:
Irreflexivity: f(x, x) = false.
Antisymmetry: If f(x, y) then !f(y, x).
Transitivity: If f(x, y) and f(y, z) then f(x, z).
Transitivity of Equivalence: Let equal(x, y) = !f(x, y) && !f(y, x). If equal(x, y) and equal(y, z) then equal(x, z).
Methods
Define operator<()
This method can be used if you want objects of a custom class to be able to be sorted naturally just as usual primitive types. If you want ascending order then return <
otherwise >
.


The output will be as follows:


But there are also other usages for particular containers using primitive types, especially when you try to customize the behavior of the order for the primitive types: sort, set and map, and priority_queue.
Set and map


The out put will be as follows:


Priority_queue
 primitive types including int, float, …, and pair;
cmpClass
for comparer;cmpFunction
for comparer.


The output will be as follows:


 a more complex usage for funcCmp.


Basics
 Access the inner map via the outer map


Always welcome new ideas and practical
tricks, just leave them in the comments!