[英]std::less<> not working with my std::map
我想用我自己的結構'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 );
}
};
錯誤:
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> ]
任何人都能看到導致問題的原因嗎?
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 );
}
有非const版本的operator==
, operator>
沒有意義,那些也應該是const
。
正如ildjarn在下面指出的那樣,這是一個明顯的例子,您可以將這些運算符實現為自由函數而不是成員函數。 通常,您應該更喜歡這些運算符作為自由函數,除非它們需要是成員函數。 這是一個例子:
bool operator<(const Point2& lhs, const Point2& rhs)
{
return (lhs.x + lhs.y) < (rhs.x + rhs.y);
}
operator<
應該定義為const
,實際上你的其他比較運算符也是如此,一般來說,任何不改變其類的方法:
bool Point2::operator== (const Point2& b) const
{
return ( x == b.x && y == b.y);
}
bool Point2::operator< (const Point2& b) const
{
return ( x+y < b.x+b.y );
}
bool Point2::operator> (const Point2& b) const
{
return ( x+y > b.x+b.y );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.