use*_*012 4 delphi sorting generics
我刚刚开始对此感到困惑.
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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
现在我想用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));
Run Code Online (Sandbox Code Playgroud)
我的知识严重缺乏这方面的东西.我从Delphi收到错误
"不兼容的类型:'System.Gerenics.Defaults.TComparison和'Procedure'
我在这做错了什么?
比较函数必须返回一个Integer值.它定义如下:
type
TComparison<T> = reference to function(const Left, Right: T): Integer;
Run Code Online (Sandbox Code Playgroud)
您的函数返回错误的类型.
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
)
);
Run Code Online (Sandbox Code Playgroud)
或者如果你想让它更简单,你可以委托默认的双倍比较器:
TArray.Sort<TNode>(
Node,
TComparer<TNode>.Construct(
function(const Left, Right: TNode): Integer
begin
Result := TComparer<Double>.Default.Compare(Left.HCost, Right.HCost);
end
)
);
Run Code Online (Sandbox Code Playgroud)