The comparison function which std::map
uses to sort the elements must adhere to strict weak ordering. But your implementation doesn't do it. As per your implementation, when all members (a, b, c) are equal, your operator<
returns true
. In other words, (1,1,1) < (1,1,1)
returns true
. Does it make sense? No.
An easy fix is this:
bool operator<(const CTest & l, const CTest & r)
{
if(l.a < r.a) return true;
else if(l.a > r.a) return false;
if(l.b < r.b) return true;
else if(l.b > r.b) return false;
return l.c < r.c;
}
That is too verbose. Instead of <
, if you use !=
, the above will reduce to this:
bool operator<(const CTest & l, const CTest & r)
{
if(l.a != r.a) return l.a < r.a;
else if(l.b != r.b) return l.b < r.b;
return l.c < r.c;
}
Well, that is still verbose, you can implement it as:
bool operator<(const CTest & l, const CTest & r)
{
return std::tie(l.a,l.b,l.c) < std::tie(r.a,r.b,r.c);
}
The std::tie
function returns std::tuple
whose operator<
implements strick weak ordering, so take advantage of this fact.