【发布时间】:2013-07-19 16:07:37
【问题描述】:
我尝试使用定义为的地图:
map<Vertex,unsigned int> _addedVertices;
现在当我使用 find 函数检查顶点是否已经在里面时 我用不同的信息得到了一个指向错误顶点的迭代器,所以我尝试了以下方法:
map<Vertex,unsigned int,cmpByVertexFields> _addedVertices;
这没有帮助。
我在 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;
}
但没有任何效果。 例子: 我插入了一个包含 (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();
}
};
【问题讨论】:
-
您的小于
operator<没有实现 strict weak ordering。这是std::map正常运行的要求。 -
我第一次只使用了 x
-
顺便说一句,您根本不需要 operator == 来使用地图的查找
-
我建议您阅读有关字典顺序的内容。基本上一个有 N 个字段的结构有点像一个有 N 个字符的字符串,现在用你的运算符比较“ab”和“ba”:
"ab" < "ba"<=>'a' < 'b' and 'b' < 'a'true and false@987654332 @,但我们知道“ab”小于“ba”:)
标签: c++ map operator-overloading