C++ Map<>.find() overloading for different class
c++, dictionary, operator-overloading
Solution
This is your culprit
bool operator<(const Vertex &otherV)const{
return(_x<otherV._x && _y<otherV._y && _z<otherV._z);
}
This doesn't yield strict weak ordering.
You need something like this
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;
}
Or, equivalently and more conveniently, compare them as tuples, using std::tie
bool operator<(const Vertex &otherV)const{
return std::tie(x_, y_, z_) < std::tie(OtherV.x_, OtherV.y_, OtherV.z_);
}
Problem
I try to use a map which is defined as : ``` map<Vertex,unsigned int> _addedVertices; ``` now when I use the find function to check if a vertex is already inside I get an iterator to a wrong vertex with different information, so I have tried the following : ``` map<Vertex,unsigned int,cmpByVertexFields> _addedVertices; ``` which didn't help. also I have the following overloaded functions inside the Vertex class. ``` 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; } ``` but nothing works. Example: I've inserted a vertex containing (0.2,0.1,0.4) and next thing I use is the find function with (0.2,0.15,0.41) the iterator I get is of the first vertex instead of map.end(). What did I forget to define? Thanks edit: 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(); } }; ```