排序 – Delphi Generics:TArray.Sort
发布时间:2020-12-15 09:26:27 所属栏目:大数据 来源:网络整理
导读:我刚刚开始对此感到困惑. PNode = ^TNode;TNode = record Obstacle : boolean; Visited : boolean; GCost : double; // Distance from Starting Node HCost : double; // Distance from Target Node x : integer; y : integer; vecNeighBour : array of PNod
|
我刚刚开始对此感到困惑.
PNode = ^TNode; TNode = record Obstacle : boolean; Visited : boolean; GCost : double; // Distance from Starting Node HCost : double; // Distance from Target Node x : integer; y : integer; vecNeighBour : array of PNode; Parent : PNode; end; OnFormShow我填充数组: SetLength(Node,4,4);
Image1.Height:=Length(Node)*50;
Image1.Width:=Length(Node)*50;
for x := Low(Node) to High(Node) do
for y := Low(Node) to High(Node) do
begin
Node[x,y].Obstacle:=false;
Node[x,y].Visited:=false;
Node[x,y].GCost:=infinity;
Node[x,y].HCost:=infinity;
Node[x,y].x:=x;
Node[x,y].y:=y;
end;
现在我想用HCost对这个数组进行排序,所以我尝试了这个. TArray.Sort<TNode>(Node,TComparer<TNode>.Construct(
function(const Left,Right: TNode): double
begin
if Left.HCost > Right.HCost then
Result:=Left.HCost
else
Result:=Right.HCost;
end));
我的知识严重缺乏这方面的东西.我从Delphi收到错误
我在这做错了什么? 解决方法
比较函数必须返回Integer值.它定义如下:
type TComparison<T> = reference to function(const Left,Right: T): Integer; 您的函数返回错误的类型. function CompareDoubleInc(Item1,Item2: Double): Integer;
begin
if Item1=Item2 then begin
Result := 0;
end else if Item1<Item2 then begin
Result := -1
end else begin
Result := 1;
end;
end;
....
TArray.Sort<TNode>(
Node,TComparer<TNode>.Construct(
function(const Left,Right: TNode): Integer
begin
Result := CompareDoubleInc(Left.HCost,Right.HCost);
end
)
);
或者如果你想让它更简单,你可以委托默认的双倍比较器: TArray.Sort<TNode>(
Node,Right: TNode): Integer
begin
Result := TComparer<Double>.Default.Compare(Left.HCost,Right.HCost);
end
)
);
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
