使用TArray <Myrectype>对大数字进行排序

JRG*_*JRG 3 arrays delphi sorting

当我在比较中有大数字时,TArray.Sort不起作用的原因是什么?

我的代码如下(Delphiy Tokyo):

Interface

Type 
 RCInd = record
           Num              : Integer;
           Ger              : Integer;           
           Confirmed        : Boolean;
           Total            : Real;
   End;

   TArrInd = TArray<RCInd>;

   Procedure SortInd  (Var PArrayInd  : TArrInd);

Implementation  

Procedure SortInd  (Var PArrayInd  : TArrInd);    
begin
  TArray.Sort<RCInd>( PArrayInd,TComparer<RCInd>.Construct
                       ( function (Const Rec1, Rec2 : RCInd) : Integer 
                         begin
                           Result := - ( Trunc(Rec1.Total) - Trunc(Rec2.Total) );
                         end )
                       );
end;

......
Run Code Online (Sandbox Code Playgroud)

当Rec1.Total和Rec2.Total的值为整数限制时,此排序工作正常,但是当值超过整数限制时排序过程不起作用!它在PArrayInd中生成一组未排序的数据.

有谁帮我理解这里发生了什么?请提前!

Dav*_*nan 9

问题是溢出问题.实数值溢出整数类型.

比较函数意味着返回负数表示小于,正数.表示大于和零表示相等.您的使用算术是导致问题的原因,因为它会溢出.而是使用比较运算符.

function(const Rec1, Rec2: RCInd): Integer
begin
  if Rec1.Total < Rec2.Total then
    Result := 1
  else if Rec1.Total > Rec2.Total then
    Result := -1
  else
    Result := 0;
end;
Run Code Online (Sandbox Code Playgroud)

这个问题中的问题是尝试将实数值拟合为整数,但即使您有整数数据,也不应将算术用于比较函数.考虑表达式

Low(Integer) - 1
Run Code Online (Sandbox Code Playgroud)

这导致溢出.作为一般原则,始终使用比较运算符来实现比较功能.