I have this type which is basically a
struct { int x,y,z; }
that I want to use as a key for a stl map. Since it's a custom type, I need to implement the operator< for the map to do it's compare magic.
I'm having a hard time coming with the function that will allow that. So far, I've tried :
return X < v.X && Y < v.Y && Z < v.Z;
which is not working at all, and
return X*X+Y*Y+Z*Z < v.X*v.X+v.Y*v.Y+v.Z*v.Z;
which gives this shape instead of a square:
Keep in mind, the x,y or z value could be negative, which further invalidates the later solution.
Anyone have any idea how to implement such feature?
I assume you just want any stable order so an ordered container will work.
if ( X != v.X ) return X < v.X;
if ( Y != v.Y ) return Y < v.Y;
return Z < v.Z;
What this does: you order based on X unless the X's are equal, if so you order on Y, etc.
You don't need operator<
, and you shouldn't implement it in cases where the semantics of the operator are not natural to all people working in the same domain to avoid confusion. Someone else might have a different interpretation of what less means, compare two points with the provided operator<
and get confused with the result.
You are better off providing a comparison operator for your specific map:
struct compareXYZ : std::binary_function<Point,Point,bool> {
bool operator()( Point const & l, Point const & r ) const {
return l.x < r.x
|| (l.x == r.x) && (l.y < r.y)
|| (l.x == r.x) && (l.y == r.y) && l.z < r.z;
}
};
std::map< Point, Value, compareXYZ> theMap; // uses XYZ comparison
This way it is clear for users of the map how points will be ordered in the container (say for linear iteration) and the lack of operator<
will be less surprising than the presence of an operator that yields a random result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With