The Comparison Criterion
This lesson talks about the rules followed by ordered associative containers when comparing the values inside them.
The default comparison criterion of the ordered associative containers is std::less
. If you want to use a user-defined type as the key, you have to overload the operator <
. It’s sufficient to overload the operator <
for your data type because the C++ runtime compares, with the help of the relation (! (elem1<elem2 || elem2<elem1))
, two elements for equality.
You can specify the sorting criterion as a template argument. This sorting criterion must implement a strict weak ordering.
ℹ️ Strict weak ordering
Strict weak ordering for a sorting criterion on a setS
is given if the following requirements are met.
- For
s
fromS
has to hold, thats < s
is not possible.- For all
s1
ands2
fromS
must hold: Ifs1 < s2
, thens2 < s1
is not possible.- For all
s1
,s2
ands3
withs1 < s2
ands2 < s3
must hold:s1 < s3
.- For all
s1
,s2
ands3
withs1
not comparable withs2
ands2
not comparable withs3
must hold:s1
is not comparable withs3
.
In opposite to the definition of the strict weak ordering, the usage of a comparison criterion with strict weak ordering is a lot simpler for a std::map
.
Get hands-on with 1400+ tech skills courses.