I know it is bad practice to use equality instead of equivalence when sorting a map.
//Equality
bool isEqual(const A& a1, const A& a2 )
{
return a1 == a2 ;
}
However I have a couple of very involved classes that I want to map and I have defined operator== for these classes, but not operator<.
Could anyone give me good reasons not to use operator== for map comparisons? I can not think of a example where it would break down in my class (I can add my class source code if needed)
Also should I just bite the built and write the new operators< :-/ ?
I would do something like this for my map.
std::map<A,B,isEqual> ex1;
Also would
ex1.find(A);
Now use equality instead of equivalence?
Because
std::map,std::setand theirmultisiblings are sorted structures as per the C++ standard, and equality cannot be used for sorting. On the other hand, strict weak ordering can be used to determine equality.As to why the structures are sorted, the standard requires that insertion and lookup be of logarithmic complexity, which is achievable by using a binary search tree. The only use for an equality comparison in such a structure is to test for the existence of an element.
If you only had equality comparison, then element lookup would have to traverse the structure, making a comparison each time until the element is found, resulting in linear time complexity.
If you did this
then the map’s comparison would not satisfy strict weak ordering, so neither the sorting of the map nor the element lookup would work. So iisn’t just bad practice, it just doesn’t work at all. You have to either implement
operator<or provide a comparison functor, and which ever one you chose has to implement strict weak ordering. There is simply no way around that.