How to override opCmp when two different sorts are needed?

BCS ao at pathlink.com
Tue Aug 14 13:40:38 PDT 2007


Reply to John,

> 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.
> 

you could try some dirty hacks:

// what you want to sort
class Foo { int myCmp(Object o){...} }

// struct of same size with my opCmp
struct FooWrap 
{
Foo f;
int opCmp(Object o){return f.myCmp(o);}
}


Foo[] f = ...;

// overlay array with new struct array and sort that
(cast(FooWrap*)f.ptr)[0..f.length].sort





More information about the Digitalmars-d mailing list