I’m aware that STL associative containers (and other containers being sorted I would guess) use the sorting criterion to test for equality.
The sorting criterion for containers defaults to st::less, so that would make the equality test for a container:
if (! (lhs < rhs || rhs < lhs))
or something similar. I had a couple questions about this…
First of all, it seems like a strangely inefficient way to compare for equality – why does the STL do it like this? I would have expected STL containers to just take an extra default parameter for equality instead.
My second question is more about the evaluation of the if statement above in general. In C++, how much of that statement would be evaluated (lhs > rhs) was true? Would it stop trying after evaluating the side that failed thus saving some efficiency? If so, which part of the expression is evaluated first?
In “Effective STL,” Scott Meyers has an extensive discussion about this in Item 19:
Equality, as you might expect, is based on
operator==.Equivalence “is based on the relative ordering of object values in a sorted range… Two objects have eqivalent values in a container
cif neither precedes the other inc‘s sort order.”Meyers expresses it this way:
Meyers then restates:
As for why the STL does it this way:
Read Item 19 (which spans the better part of 6 pages) for yourself to get the full flavor.