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)。謝謝 –