4
A
回答
6
你会想要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));
}
7
使用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();
}
这将输出:
Before sorting:
3142
After sorting:
1234
相关问题
- 1. 如何按对象值对对象数组进行排序?
- 2. 如何在Javascript中对数组中的对象进行排序?
- 3. 如何对其中的日期对象数组进行排序?
- 4. 如何对数组中的日期对象进行排序?
- 5. 如何对集合MongoDB中的对象数组进行排序?
- 6. 如何按数字升序对对象数组进行排序?
- 7. 如何在Java中对对象数组进行排序
- 8. 如何在Visual C#中对对象数组进行排序?
- 9. 如何在javascript中对这个对象数组进行排序?
- 10. 如何通过PHP中的对象字段对对象数组进行排序?
- 11. 如何基于对象键值对PHP数组中的对象进行排序?
- 12. 如何根据对象的属性对数组进行排序?
- 13. Symfony2 - 如何对合并的对象数组进行排序?
- 14. 如何对类对象的数组进行排序?
- 15. 如何对包含对象的三维数组进行排序?
- 16. AS3对一组对象进行排序?
- 17. 如何对对象数组进行排序?
- 18. 如何基于任意对象值对数组进行排序?
- 19. 如何对对象数组进行排序?
- 20. 如何用对象对多维数组进行排序?
- 21. 如何对对象数组进行排序
- 22. 如何通过element.name对javascript对象数组进行排序
- 23. 如何通过NSString属性对对象数组进行排序
- 24. 如何对json对象进行排序?
- 25. 如何通过对象的属性对对象数组进行排序?
- 26. 如何通过每个对象的属性对对象数组进行排序
- 27. 如何根据对象的值对对象数组进行排序?
- 28. 如何对数组进行排序?
- 29. 如何对PHP数组进行排序?
- 30. php,如何对数组进行排序?
为什么进口'std.algorithm.sort'而不是仅仅用'array.sort'? –
@Pedro,很难说如果这是官方的,但应该是,数组的排序属性已被弃用。 std.algorithm.sort是通用的,使用自定义范围和自定义排序功能。 –
@hethegreat啊,发现官方计划弃用它:[弃用功能](http://dlang.org/deprecate.html)。谢谢 –