简体   繁体   中英

Implementing operator< for x,y,z coordinate

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.

A 3-dimensional vector can be compared using the length of the vector

SquareRoot(X*X + Y*Y + Z*Z);

This allows for negative directions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM