TITLE: sorting using STL (Newsgroups: comp.lang.c++, 25 Jun 98) CHUGH: Kevin P Chugh > hi- i'm trying to use the STL set template. i want to use my own classes > and so i need to override the < operator. but, i want to use a set > of pointers, not a set of objects. my question is this- how do i > create a < operator for pointers to my objects. i've tried this: > > bool operator < (MyClass *c1,MyClass *c2) > { > return (c1->numbernumber); > } > > but the compiler (borland 5.0) complains that this operator must > be a member function or class. > > so i tried writing it as a friend, but that didn't work either. > > am i correct in assuming that if i want a less than operator for > two pointers to a class type that i need a non-member operator- if > this is true, how do i write one? BECKER: Pete Becker Back up and ask the right question. The question is, how do I define my own ordering operation for items in an STL set? And the answer is, write a class for the set to use instead of the default less, which uses operator<. You do it like this: struct lessThan : binary_function { public: bool operator()(const MyClass *m1, const MyClass *m2) const { return /* whatever makes sense */; } } Then you create a set with this class as its comparator: set items; Now your set will be sorted in accordance with the rule that you wrote in lessThan::operator(). Make sure that it defines a partial ordering, though: don't write something that at one time says that o1 is less than o2 and at another time says that o1 is greater than o2.