I stumbled upon a problem I cannot solve regarding maps. As we know, maps require the two type of variables it is gonna handle i.e. map<int, string>, but what about custom types?
Let's say I have an object called 'Point' which consists in two variables, x and y. Is it feasible to declare a map like: map<Point,int>?. Please look at the code below
The compiler does not know how to compare two objects of your class. You can either define an operator<() for your class or you can define a function pointer or function object and pass it to the map constructor.
See here: http://www.cplusplus.com/reference/map/map/?kw=map
Based on norm b's advice, I overloaded the operator<() in this manner:
1 2 3 4 5 6 7
booloperator<(const Point& a, const Point& b)
{
// Usage of std::tie :
// compares a.x to b.x,
// then a.y to b.y
return std::tie(a.x, a.y) < std::tie(b.x, b.y);
}
Once this detail is added to the code, it runs smoooooth...
EDIT: wow nice, you did it the right way before I could even tell you how! Nice work ;)
For a point class, there's generally no good/agreed way to compare points for ordering - just pick a method and use it. This is the most common implementation:
1 2 3 4 5 6 7 8
#include <tuple> //you need C++11
//...
booloperator<(Point const &a, Point const &b)
{
return std::tie(a.x, a.y) < std::tie(b.x, b.y); //let std::tuple handle it for us
}