A map with a struct as it's key

I wrote the following:
1
2
3
4
5
6
7
8
9
10
11
12
struct N
{
    long double x;
    long double y;
    long double r;
    friend operator<(const N &T, const N &Z)
    {
        return T.r < Z.r;
    }
};
///
map<N, long double> circles;

I was also given a list of 2000 circles that I attempted to store in the map. None of those are identical, although some may have the same radius lengths or the coordinates of their centers.

After reading the file my program with the declarations above outputted only 1355 as the circles' size. I have discovered that changing the operator declaration into:
1
2
3
4
friend operator<(const N &T, const N &Z)
{
     return T.r < Z.r || T.x < Z.x || T.y < Z.y;
}

makes the program work as intended. Why is it the case that the first declaration causes the container to be faulty?
Your original operator< only compared r, so if two objects had different x and y but the same r they would be considered equal.

Your second operator< is not correct. It does not provide a consistent ordering of the objects. If you declared two objects like this
1
2
N n1 {1, 2, 1};
N n2 {1, 1, 2};
then n1 < n2 would return true, but n2 < n1 would also return true. This is a contradiction.

What you probably want is something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool operator<(const N &T, const N &Z)
{
	if (T.r != Z.r)
	{
		return T.r < Z.r;
	}
	else if (T.x != Z.x)
	{
		return T.x < Z.x;
	}
	else
	{
		return T.y < Z.y;
	}
}
Last edited on
Isn't the operator only used for assessing in which part of the container the data should be put? Of course, circles with the same r values would be thought of as equal (as in the order of the structs does not matter), but how come the program ignores the other parameters?
No. By default, the < operator is used to put the elements in order (which is how std::map can look up the elements so quickly) and also to know if two elements are the same (it only stores one value per key).
Last edited on
Thank you!
Topic archived. No new replies allowed.