2013-11-25 113 views

回答

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)); 
} 
+0

爲什麼進口'std.algorithm.sort'而不是僅僅用'array.sort'? –

+1

@Pedro,很難說如果這是官方的,但應該是,數組的排序屬性已被棄用。 std.algorithm.sort是通用的,使用自定義範圍和自定義排序功能。 –

+0

@hethegreat啊,發現官方計劃棄用它:[棄用功能](http://dlang.org/deprecate.html)。謝謝 –

7

使用std.algorithm.sortopCmp超載:

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 
相關問題