您需要定义点项目的顺序。
这可以通过不同的方式完成:
为 Point 重载 operator <
您可以提供< 运算符的重载,其原型为:
bool operator < (const Point & p_lhs, const Point & p_rhs) ;
例如,对于我的测试,我使用了以下一种:
bool operator < (const Point & p_lhs, const Point & p_rhs)
{
if(p_lhs.getX() < p_rhs.getX()) { return true ; }
if(p_lhs.getX() > p_rhs.getX()) { return false ; }
return (p_lhs.getY() < p_rhs.getY()) ;
}
这是最简单的方法,但从语义上讲,它假定上面定义的顺序是正确的默认顺序。
提供函子
如果您不愿意提供< 运算符,或者想要拥有多个地图,每个地图都有自己的顺序,您的解决方案是为地图提供函子。这是为地图定义的第三个模板参数:
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
函子必须具有以下签名:
struct MyCompareFunctor
{
bool operator() (const Point & p_lhs, const Point & p_rhs)
{
// the code for comparison
}
} ;
所以,对于我的测试,我只写了以下内容:
struct MyCompare
{
bool operator() (const Point & p_lhs, const Point & p_rhs)
{
if(p_lhs.getX() > p_rhs.getX()) { return true ; }
if(p_lhs.getX() < p_rhs.getX()) { return false ; }
return (p_lhs.getY() > p_rhs.getY()) ;
}
} ;
并在我的地图中使用它:
std::map<Point, Point, MyCompare> map ;
等等……
将std::less 专门用于Point
我认为这样做没有任何意义,但知道总是很好:您可以为您的 Point 类专门化 std::less 模板结构
#include <functional>
namespace std
{
template<>
struct less<Point> : binary_function <Point,Point,bool>
{
bool operator() (const Point & p_lhs, const Point & p_rhs)
{
if(p_lhs.getX() < p_rhs.getX()) { return true ; }
if(p_lhs.getX() > p_rhs.getX()) { return false ; }
return (p_lhs.getY() < p_rhs.getY()) ;
}
} ;
}
至少就地图而言,这与重载operator < 具有相同的效果。
至于上面的operator < 解决方案,从语义上讲,这个解决方案假定上面定义的顺序是正确的默认顺序,就std:less 而言。
请注意,默认的std::less 实现调用的是模板类型的operator <。一个给出的结果与另一个不同可能被视为语义错误。