Comparison Operators Overloading

Comparison Operators Overloading

This topic is about Comparison Operators Overloading.

The following table shows the list of comparsion operators and its purpose.

Function NameOperatorPurpose
opCmp<whether before
opCmp<=whether not after
opCmp>whether after
opCmp>=whether not before

Comparison operators are used for sorting arrays. The following example shows how to use comparion operators.

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]); 
}

When the above code is compiled and executed, it produces the following result −

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 

In this topic we learned about Comparison Operators Overloading. To learn more, Click Here.

This Post Has One Comment

Leave a Reply