发布于 2015-08-16 14:49:54 | 93 次阅读 | 评论: 0 | 来源: 网络整理

下表显示的比较运算符,其目的列表。

函数名 运算符 目的
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:%sn", 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
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务