Search code examples
arrayssortingd

How to sort array of objects in Dlang?


How do I sort an array of user-defined objects in D?

Coming from a C++ background, I suppose you'd have to declare an operator overload for the type stored in the array, or use a comparator function...

An example of how to do it would be much appreciated.


Solution

  • You'll want std.algorithm.sort which uses a < b by default, so your class can override opCmp to take advantage of that.

    Update: Just a alternative to glampert's example.

    import std.algorithm;
    import std.stdio;
    
    class Test {
    
        int x;
    
        this(int x)
        {
            this.x = x;
        }
    }
    
    void main()
    {
        Test[] array = [new Test(3), new Test(1), new Test(4), new Test(2)];
    
        writeln("Before sorting: ");
        writeln(array.map!(x=>x.x));
    
        sort!((a,b)=>a.x < b.x)(array); // Sort from least to greatest
    
        writeln("After sorting: ");
        writeln(array.map!(x=>x.x));
    }