std :: less <>不能使用我的std :: map

xcr*_*ypt 4 c++ stl std

我想用我自己的结构'Point2'作为键来制作一个地图,但是我得到了错误,我不知道是什么导致了它,因为我为Point2结构声明了一个'operator <'.

码:

std::map<Point2, Prop*> m_Props_m;
std::map<Point2, Point2> m_Orders;

struct Point2
{
    unsigned int Point2::x;
    unsigned int Point2::y;

Point2& Point2::operator= (const Point2& b)
    {
        if (this != &b) {
            x = b.x;
            y = b.y;
        }
        return *this;
    }

    bool Point2::operator== (const Point2& b)
    {
        return ( x == b.x && y == b.y);
    }

    bool Point2::operator< (const Point2& b)
    {
        return ( x+y < b.x+b.y );
    }

    bool Point2::operator> (const Point2& b)
    {
        return ( x+y > b.x+b.y );
    }
};
Run Code Online (Sandbox Code Playgroud)

错误:

1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Point2' (or there is no acceptable conversion)
1>c:\testing\project\point2.h(34): could be 'bool Point2::operator <(const Point2 &)'
1>while trying to match the argument list '(const Point2, const Point2)'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const'
1>          with
1>          [
1>              _Ty=Point2
1>          ]
Run Code Online (Sandbox Code Playgroud)

任何人都能看到导致问题的原因吗?

Cha*_*had 9

std::map期望const版本operator <:

// note the final const on this line:
bool Point2::operator< (const Point2& b) const
{
    return ( x+y < b.x+b.y );
}
Run Code Online (Sandbox Code Playgroud)

它没有意义的有非const版本operator==,operator>那些应该是const为好.

正如ildjarn在下面指出的那样,这是一个明显的例子,您可以将这些运算符实现为自由函数而不是成员函数.通常,您应该更喜欢这些运算符作为自由函数,除非它们需要是成员函数.这是一个例子:

bool operator<(const Point2& lhs, const Point2& rhs)
{
    return (lhs.x + lhs.y) < (rhs.x + rhs.y);
}
Run Code Online (Sandbox Code Playgroud)