[英]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. 我将3D向量用作C ++地图容器中的键,为此我必须实现两个向量的比较。 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.
但是,当两个向量不同但其大小相同时,就会出现问题,从而导致C ++映射容器中的键被覆盖。
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. 除了简单地比较它们的
magnitude
您还可以使用std::tuple
进行比较 ,该比较具有按字典顺序定义的比较运算符 。
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 还要注意,如果您在类中定义
operator<
,则无需制作此结构,因为map
的模板参数是
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<
因此,由于您定义了
operator<
因此将定义std::less
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.