How to override opCmp when two different sorts are needed?
Bill Baxter
dnewsgroup at billbaxter.com
Tue Aug 14 16:27:55 PDT 2007
Jarrett Billingsley wrote:
> "John Bartelt" <bartelt at cox.net> wrote in message
> news:f9quel$rou$1 at digitalmars.com...
>> I have a class that contains two variables. Sometimes I need to sort an
>> array of the class based on variable 1, and later in the same progam sort
>> the array based on variable 2.
>>
>> Can someone give me an idea of how to do this (smartly, efficiently,
>> cleverly, polymorphically, ...)?
>>
>> Best idea that I've had so far is to use a static flag in the class to
>> indicate which sort is desired, and then to have the overloaded opCmp()
>> check the flag before comparing.
>
> Write your own sort routine which takes a given predicate. :\
>
> Tango provides such a routine in tango.core.Array; phobos provides no such
> analogue. With phobos, either write your own routine, or use
> std.c.stdlib.qsort. I'll let you decide which is more elegant.
There's also Oskar's sort w/predicate
http://www.csc.kth.se/~ol/array.d
I thought the question was more about how to organize the software to
control the change in behavior though. For that I think you'll have to
think about who "owns" the change in behavior and to whom the change
should be visible to.
--bb
More information about the Digitalmars-d
mailing list