set and operators

G

Giulio Veronesi

Hi all,

struct MyStruct {
int x, y;
};

bool operator<(const MyStruct& a1, const MyStruct& a2)
{
return ( (a1.x < a2.x) ||
( (a1.x == a2.x) && (a2.y < a2.y) ) );
}

typedef set<MyStruct> MySet;

Which other operators have I to overload to manage MySet? More
precisaly, when I insert something in the set, if the x field is equal
to another x field of another structure previous inserted in the set,
the second one is not inserted. I would like that a structure is not
inserted if and only if both its x and y filed are equals to x and y of
another structure in the set.

Thanks in advance,
Giulio
 
V

Victor Bazarov

Giulio said:
struct MyStruct {
int x, y;
};

bool operator<(const MyStruct& a1, const MyStruct& a2)
{
return ( (a1.x < a2.x) ||
( (a1.x == a2.x) && (a2.y < a2.y) ) );
}

typedef set<MyStruct> MySet;

Which other operators have I to overload to manage MySet?

None. Assignment is useful, but the default one should suffice.
> More
precisaly, when I insert something in the set, if the x field is equal
to another x field of another structure previous inserted in the set,
the second one is not inserted. I would like that a structure is not
inserted if and only if both its x and y filed are equals to x and y of
another structure in the set.

All that should be expressed in the operator <. In your case, for a set
of your structs, two structures k and m are considered equivalent iff
(!(k < m) && !(m < k)) evaluates to true.

V
 
M

Markus Moll

John said:
Nope don't see it.

Okay:

"a2.y < a2.y" is always false.
That makes "(a1.x == a2.x) && (a2.y < a2.y)" false.
Therefore, effectively, you return a1.x < a2.x

A simple typo, but it breaks your order...

hth
Markus
 
J

John Harrison

Markus said:
John Harrison wrote:




Okay:

"a2.y < a2.y" is always false.
That makes "(a1.x == a2.x) && (a2.y < a2.y)" false.
Therefore, effectively, you return a1.x < a2.x

A simple typo, but it breaks your order...

Aargh! I blame those spurious parens.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top