D-programming-comparison-operators-overloading
提供:Dev Guides
比較演算子のオーバーロード
次の表に、比較演算子とその目的のリストを示します。
Function Name | Operator | Purpose |
---|---|---|
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