2013-11-25 116 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 
相关问题