Std :: less <> does not work with my std :: map

I wanted to create a map with my own string "Point2" as a key, however I get errors and I don't know what causes it since I declared "operator <" for the structure of Point2.

Code:

 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 = bx; y = by; } return *this; } bool Point2::operator== (const Point2& b) { return ( x == bx && y == by); } bool Point2::operator< (const Point2& b) { return ( x+y < b.x+by ); } bool Point2::operator> (const Point2& b) { return ( x+y > b.x+by ); } }; 

Error:

 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> ] 

Can anyone see the cause of the problem?

+4
source share
2 answers

std::map expects a version of const operator < :

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

It does not make sense to have non-constant versions of operator== , operator> , they should also be const .

As ildjarn points out below, this is an explicit case where you can implement these operators as free functions instead of member functions. Generally, you should prefer these operators as free functions if they should not be member functions. Here is an example:

 bool operator<(const Point2& lhs, const Point2& rhs) { return (lhs.x + lhs.y) < (rhs.x + rhs.y); } 
+9
source

operator< should be defined as const , in fact, your other comparison operators should be the same, and generally any method that does not mutate its class:

 bool Point2::operator== (const Point2& b) const { return ( x == bx && y == by); } bool Point2::operator< (const Point2& b) const { return ( x+y < b.x+by ); } bool Point2::operator> (const Point2& b) const { return ( x+y > b.x+by ); } 
+3
source

Source: https://habr.com/ru/post/1383956/


All Articles