Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of objects in Dlang?

Tags:

arrays

sorting

d

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.

like image 783
glampert Avatar asked Nov 25 '13 05:11

glampert


2 Answers

Using std.algorithm.sort and opCmp overload:

import std.algorithm;
import std.stdio;

class Test 
{
    int x;

    this(int x)
    {
        this.x = x;
    }

    int opCmp(ref const Test other) const
    {
        if (this.x > other.x)
        {
            return +1;
        }
        if (this.x < other.x)
        {
            return -1;
        }
        return 0; // Equal
    }
};

void main()
{
    Test[] array = [new Test(3), new Test(1), new Test(4), new Test(2)];

    writeln("Before sorting: ");
    for (int i = 0; i < array.length; ++i)
    {
        write(array[i].x);
    }
    writeln();

    sort(array); // Sort from least to greatest using opCmp

    writeln("After sorting: ");
    for (int i = 0; i < array.length; ++i)
    {
        write(array[i].x);
    }
    writeln();
}

Which will output:

Before sorting:
3142
After sorting:
1234
like image 68
glampert Avatar answered Sep 30 '22 20:09

glampert


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));
}
like image 38
he_the_great Avatar answered Sep 30 '22 20:09

he_the_great