如何在D中对用户定义的对象数组进行排序?
来自C++背景,我想你必须为存储在数组中的类型声明一个运算符重载,或者使用比较器函数......
如何做到这一点的一个例子将非常感激.
你需要std.algorithm.sort默认使用<b,所以你的类可以覆盖opCmp来利用它.
更新:只是glampert示例的替代方案.
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));
}
Run Code Online (Sandbox Code Playgroud)
使用std.algorithm.sort和opCmp过载:
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();
}
Run Code Online (Sandbox Code Playgroud)
哪个会输出:
Before sorting:
3142
After sorting:
1234
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |