sorting a mutable array of immutable objects

Jeff Thompson via Digitalmars-d digitalmars-d at puremagic.com
Wed Apr 20 03:32:42 PDT 2016


On Wednesday, 20 April 2016 at 09:54:13 UTC, Jeff Thompson wrote:
> I can create a mutable array of immutable objects, thanks to 
> the answers to my other question 
> https://forum.dlang.org/post/nf57f5$e6v$1@digitalmars.com .
>
> Now I want to sort the array.

I found a solution, but I'm not sure it is the best way. Instead 
of overriding opCmp, class C just defines a static comparison to 
use with sort (which automatically works with Rebindable). Is 
there a way to do this where I don't need to specify C.isLess 
every time I sort?

class C {
   this(int x) immutable { this.x = x; }
   static bool isLess(const C a, const C b) @safe pure nothrow { 
return a.x < b.x; }
   int x;
}

void
main(string[] args)
{
   auto array = new Rebindable!(immutable(C))[2];
   array[0] = new immutable C(20);
   array[1] = new immutable C(10);
   sort!(C.isLess)(array);
}



More information about the Digitalmars-d mailing list