我正试图传递一个自定义类的重载作为std::map
的比较器。
这里有一些代码和错误可以帮助你帮助我:
这是Position.hpp
#ifndef POSITION_HPP_
# define POSITION_HPP_
class Position
{
public:
int _x;
int _y;
Position(){}
Position(int x, int y)
{
_x = x;
_y = y;
}
void setPosition(Position &newpos)
{
_x = newpos._x;
_y = newpos._y;
}
int getX()
{
return _x;
}
int getY()
return _y;
}
void setX(int x)
{
_x = x;
}
void setY(int y)
{
_y = y;
}
struct cmpIsSame{
inline bool operator==(const Position& pos)
{
if (pos._x == _x && pos._y == _y)
return true;
return false;
}
};
inline Position& operator=(const Position& pos)
{
_x = pos._x;
_y = pos._y;
return *this;
}
};
#endif
这是GameEngine.hh 中的地图声明
private:
std::map<Position, Case, Position::cmpIsSame> _cases;
这是一个错误:
Position.hpp: In member function ‘bool Position::cmpIsSame::operator==(const Position&)’:
Position.hpp:17:7: error: invalid use of non-static data member ‘Position::_x’
int _x;
^
Position.hpp:52:21: error: from this location
if (pos._x == _x && pos._y == _y)
^
Position.hpp:18:7: error: invalid use of non-static data member ‘Position::_y’
int _y;
^
Position.hpp:52:37: error: from this location
if (pos._x == _x && pos._y == _y)
^
能帮忙吗?
关于错误
在operator==
的实现中,您尝试访问封闭类的成员_x
等。你在那里无法访问它们。在类中嵌入类是命名空间问题,而不是成员访问问题。
只提供一个自由函数或一个提供比较的函子会更容易。
关于map
中密钥的比较
std::map
的密钥比较的定义是std::less
,默认情况下它调用operator<
。只为您使用的密钥实现一个重载的operator<
可能会更容易。
bool operator<(const Position& lhs, const Position rhs&) {
// your implementation of "less" here...
}
关于less
的实现
这实际上取决于您和您在应用程序中使用它的方式。但是,作为第一个近似值(也是为了让代码继续运行),可以考虑使用点到原点的距离(勾股理论)(可能为0,0)。
首先,您必须使用函数对象或静态函数。但在任何情况下,你的方法都是错误的,因为比较器应该满足对应于运算符<的严格弱排序原则;。
来自C++标准(23.2.4关联容器)
3短语"钥匙等价"是指等价关系由比较和强加,而不是由键上的运算符==强加。也就是说,如果对于比较对象comp,comp(k1,k2)==false&;comp(k2,k1)==false。对于同一容器中的任意两个密钥k1和k2,调用comp(k1,k2)应始终返回相同的值。