You need to determine the order of the Point points.
This can be done in different ways:
Overload operator < for point
You can overload the < operator, the prototype of which is:
bool operator < (const Point & p_lhs, const Point & p_rhs) ;
For example, for my tests, I used the following command:
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()) ; }
This is the easiest way, but semantically assumes that the ordering described above is correct by default .
Providing Functor
If you do not want to provide an operator < or want to have several cards, each of which has its own order, your decision should provide a functor card. This is the third template parameter defined for the map:
template < class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key,T> > > class map;
The functor must have the following signature:
struct MyCompareFunctor { bool operator() (const Point & p_lhs, const Point & p_rhs) {
So, for my tests, I just wrote the following:
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()) ; } } ;
And used it on my map:
std::map<Point, Point, MyCompare> map ;
Et voilΓ ...
Specialization std::less for Point
I donβt see the point in this, but itβs always useful to know: you can specialize the structure of the std::less template for your Point class
#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()) ; } } ; }
This has the same effect as operator < overloading, at least with respect to the map.
Regarding the above operator < solution, semantically, this solution assumes that the ordering described above is the correct default value for std:less .
Note that the default implementation of std::less calls operator < template type. If you give different results than others, you can consider it as a semantic error.