Question on maps: Invalid operands to binary...

Hello programmers,

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Point
{
public:
	double x;
	double y;
	Point(double x, double y)
	{
		this->x=x;
		this->y=y;
	}
}

int main(int argc, const char * argv[])
{
	map<Point,int> myMap;
	
	Point p1(0,0);

        myMap[p1]=1;
} 


I'm receiving a compilation error: 'Invalid operands to binary expression ('const Point' and 'const Point').

Does anyone know why this is happening and how can I solve it? Any help would be really appreciated :).

Cheers!
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
@norm b: Thanks for your answer!

Based on norm b's advice, I overloaded the operator<() in this manner:

1
2
3
4
5
6
7
bool operator<(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...

Cheers!
Last edited on
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

//...

bool operator<(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
}
Last edited on
Topic archived. No new replies allowed.