In question Using char as key in stdmap there is advised to use custom compare function/functor:
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
map<char *, int, cmp_str> BlahBlah;
This allows map to detect if key A is less than key B. But for example map<>::find() returns end if element is not found, and iterator to it if it is found. So map knows about equivalence, not only less-than. How?
The equality condition for two keys
aandbare thata<bandb<aare both false. The map itself is commonly implemented as a balanced binary tree*, so the less-than comparison is used to traverse the map from the root node until the matching element is found. When searching for a keyk, less-than comparison is used until the first element for which the comparison is false is found. If the inverse comparison is also false,khas been found. Otherwise,kis not in the map. The map only uses the less-than comparison to this purpose.Note also that
std::setuses exactly the same mechanism, the only difference being that each element is it’s own key.* strictly speaking, the C++ standard does not specify that
std::mapbe a balanced binary tree, but the complexity constraints it places on operations such as insertion and look-up mean that implementations chose structures such as red-black tree.