bob*_*obo 8 c++ math operator-overloading stdmap
我需要创建一个映射,其中空间中的特定键位置映射到对象列表. std::map
似乎是这样做的方式.
所以我在键入一个std::map
xyzVector
class Vector
{
float x,y,z
} ;
Run Code Online (Sandbox Code Playgroud)
,我正在做一个std::map<Vector, std::vector<Object*> >
.所以请注意,这里的关键不是 a std::vector
,它的对象class Vector
只是我自己制作的数学xyz向量.
为了产生"严格弱的排序",我写了以下重载operator<
:
bool Vector::operator<( const Vector & b ) const {
// z trumps, then y, then x
if( z < b.z )
{
return true ;
}
else if( z == b.z )
{
if( y < b.y )
{
// z == b.z and y < b.y
return true ;
}
else if( y == b.y )
{
if( x < b.x )
{
return true ;
}
else if( x == b.x )
{
// completely equal
return false ;
}
else
{
return false ;
}
}
else
{
// z==b.z and y >= b.y
return false ;
}
}
else
{
// z >= b.z
return false ;
}
}
Run Code Online (Sandbox Code Playgroud)
它有点长,但基本上是这样,所以任何矢量可以一直被认为小于任何其他矢量((-1,-1,-1)<( - 1,-1,1)和(-1, - 1,1)>(-1,-1,-1)例如).
我的问题是这真的是人为的,虽然我已编码并且它有效但我发现它"污染"我的Vector类(数学上)这个非常奇怪,人为的,非基于数学的"小于"的概念为矢量.
但我需要创建一个映射,其中空间中的特定键位置映射到某些对象,并且std :: map似乎是这样做的方式.
建议?开箱即用的解决方案欢迎!!
operator<
您可以为地图提供自定义比较器,而不是为您的键类定义.这是一个函数对象,它接受两个参数,true
如果第一个参数位于第二个参数之前,则返回.像这样的东西:
struct CompareVectors
{
bool operator()(const Vector& a, const Vector& b)
{
// insert comparison code from question
}
};
typedef std::map<Vector, Value, CompareVectors> VectorValueMap;
Run Code Online (Sandbox Code Playgroud)