简体   繁体   中英

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?

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<

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