# coord as key in std::map

This topic is 3714 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

What I have is this:
struct coord
{
float x, y;
};

const bool operator<( const coord& a, const coord& b )
{
if ( a.x < b.x ) return true;
else return false;
}

std::map<coord, int> my_map;

My problem is that doing
coord foo;
foo.x = 0;
foo.y = 0;
my_map[ foo ] = 5;

coord bar;
bar.x = 0;
bar.y = 1;
my_map[ bar ] = 10;

In this example, the bar key overwrites the entry of the foo key. 'foo' key along with is value is erased from the map. I understand that this must have something to do with the operator, since the keys must be unique. In what way must I change the operator to make it distinguish between the foo and bar key?

##### Share on other sites
const bool operator<( const coord& a, const coord& b ){	if ( a.x < b.x ) return true;        if ( a.x > b.x ) return false;	return a.y < b.y;}

##### Share on other sites
Your keys must be members of a well ordered set. Your less than operator does not meet this requirement since it says that (0, 1) == (0, 0) (map uses < to divine all 6 comparisons).

SiCrane's less than operator does meet this requirement.

##### Share on other sites
I was aware - from the errors I got before defining the operator - that std::map uses operator<. And I knew that I couldnt just compare on x alone, but was unsure as to how to use y in the comparison.

But it works as intended now, thanks to you both! :)

##### Share on other sites
See also "lexicographic comparison". The idea is to provide a "sorting order" for your coordinates; here, we can use "sort first by x, then by y".

• 10
• 18
• 14
• 18
• 15