nbsrujan nbsrujan - 2 months ago 25
C++ Question

Compare two 3D vectors

I am using 3D vector as key in C++ map containers.For which I have to implement comparison of two vectors. I used magnitude to compare vectors. But problem arises when two vectors are different but their magnitudes are same, which is resulting in overwriting of keys in C++ map container.

You can find small snipped of implementation.

class Vector3f
{
public:
float x, y, z;
double magnitude() const { return sqrt(x*x + y*y + z*z); }
}
std::map<Vector3f, std::vector<int>, Vector3fCompare> vector_index;

struct Vector3fCompare
{
bool operator() (const Vector3f& lhs, const Vector3f& rhs) const
{
return lhs.magnitude() < rhs.magnitude();
}
};


Is there any way to compare two vectors?

Answer

Rather than simply comparing their magnitude you can do a comparision using std::tuple which has the comparison operators defined lexicographically.

struct Vector3fCompare
{
    bool operator() (const Vector3f& lhs, const Vector3f& rhs) const
    {
        return std::make_tuple(lhs.x, lhs.y, lhs.z) < std::make_tuple(rhs.x, rhs.y, rhs.z);
    }
};

Also note that if you define operator< in your class, then you do not need to make this struct, as the template arguments for map are

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

So std::less will be defined since you defined operator<