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.
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
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With