std::map
s require a less-than (or equivalent; less<key_type>
is the default, per table 102), comparison for key types.
[C++11: 23.2.4/3]:
The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator==
on keys. That is, two keys k1
and k2
are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false
. For any two keys k1
and k2
in the same container, calling comp(k1, k2)
shall always return the same value.
So you can provide a comparator function that is not less<key_type>
, to avoid operator<
being called, but the end result as defined above must be the same. operator==
is entirely irrelevant.
#include <iostream>
#include <map>
/**
* A comparator that defines strict-weak ordering,
* but is backwards!
*/
struct Comp
{
bool operator()(const int& lhs, const int& rhs)
{ return rhs < lhs; }
};
int main()
{
{
std::map<int, char> m; // uses default less<int> comparator
m[0] = 'a';
m[1] = 'b';
m[2] = 'c';
for (auto el : m)
std::cout << el.second; // "abc"
}
{
std::map<int, char, Comp> m; // uses my own comparator defined above
m[0] = 'a';
m[1] = 'b';
m[2] = 'c';
for (auto el : m)
std::cout << el.second; // "cba" ... which is true ;)
}
}