Des*_*air 3 c++ operator-overloading map
我尝试使用定义为的地图:
map<Vertex,unsigned int> _addedVertices;
Run Code Online (Sandbox Code Playgroud)
现在,当我使用find函数检查顶点是否已经在里面时,我得到一个迭代器到一个具有不同信息的错误顶点,所以我尝试了以下内容:
map<Vertex,unsigned int,cmpByVertexFields> _addedVertices;
Run Code Online (Sandbox Code Playgroud)
这没有帮助.
我在Vertex类中有以下重载函数.
bool operator<(const Vertex &otherV)const{
return(_x<otherV._x && _y<otherV._y && _z<otherV._z);
}
bool operator==(const Vertex &otherV)const{
return _x==otherV._x && _y==otherV._y && _z==otherV._z;
}
Run Code Online (Sandbox Code Playgroud)
但没有任何作用.示例:我插入了一个包含(0.2,0.1,0.4)的顶点,接下来我使用的是查找函数(0.2,0.15,0.41)我得到的迭代器是第一个顶点而不是map.end().
我忘了定义什么?谢谢
编辑:cmpByVertexFields:
struct cmpByVertexFields {
bool operator()(const Vertex& a, const Vertex& b) const {
return a.getX()==b.getX() &&
a.getY()==b.getY() &&
a.getZ()==b.getZ();
}
};
Run Code Online (Sandbox Code Playgroud)
这是你的罪魁祸首
bool operator<(const Vertex &otherV)const{
return(_x<otherV._x && _y<otherV._y && _z<otherV._z);
}
Run Code Online (Sandbox Code Playgroud)
这不会产生严格的弱序.
你需要这样的东西
bool operator<(const Vertex &otherV)const{
if(_x != otherV.x)
return _x < otherV.x;
if(_y != otherV.y)
return _y < otherV.y;
return _z < otherV.z;
}
Run Code Online (Sandbox Code Playgroud)
或者,等效且更方便,使用std :: tie将它们作为元组进行比较
bool operator<(const Vertex &otherV)const{
return std::tie(x_, y_, z_) < std::tie(OtherV.x_, OtherV.y_, OtherV.z_);
}
Run Code Online (Sandbox Code Playgroud)