目录

Comparison Operators 重载

下表显示了比较运算符列表及其用途。

功能名称 操作者 目的
opCmp<whether before
opCmp<=whether not after
opCmp>whether after
opCmp>=whether not before

比较运算符用于排序数组。 以下示例显示如何使用比较运算符。

import std.random; 
import std.stdio; 
import std.string; 
struct Box { 
   int volume;  
   int opCmp(const ref Box box) const { 
      return (volume == box.volume ? box.volume - volume: volume - box.volume); 
   }
   string toString() const { 
      return format("Volume:%s\n", volume); 
   } 
} 
void main() { 
   Box[] boxes; 
   int j = 10; 
   foreach (i; 0 .. 10) { 
      boxes ~= Box(j*j*j); 
      j = j-1; 
   } 
   writeln("Unsorted Array"); 
   writeln(boxes);  
   boxes.sort; 
   writeln("Sorted Array"); 
   writeln(boxes); 
   writeln(boxes[0]<boxes[1]); 
   writeln(boxes[0]>boxes[1]); 
   writeln(boxes[0]<=boxes[1]); 
   writeln(boxes[0]>=boxes[1]); 
}

编译并执行上述代码时,会产生以下结果 -

Unsorted Array 
[Volume:1000 
, Volume:729 
, Volume:512 
, Volume:343 
, Volume:216 
, Volume:125 
, Volume:64 
, Volume:27 
, Volume:8 
, Volume:1 
] 
Sorted Array 
[Volume:1 
, Volume:8 
, Volume:27 
, Volume:64 
, Volume:125 
, Volume:216 
, Volume:343 
, Volume:512 
, Volume:729 
, Volume:1000 
] 
true 
false 
true 
false 
↑回到顶部↑
WIKI教程 @2018