Forum > General

How to port TArray.Sort?

(1/2) > >>

domasz:
I want to port Delphi library to Lazarus but don't know how to replace TArray.Sort. Or maybe it's gonna be in Lazarus 4.0?

Thaddy:
TArray<T> sort is in generics.collections.
I gave an example this week.
It is not quite compatible with fpc yet, but the missing features as documented in the sources for TArrayHelper are now largely resolved, so the feature can also be adapted to be Delphi compatible now.

The basic differences are small:
Delphi: TArray (w/o <T>) is a class containing only generic class methods, its equivalent in FPC is TArrayHelper<T>
You need to maintain very small code changes between them. Will add example later.

domasz:
Thank you, Thaddy. I think I got:
TArrayHelper<>.Sort(SearchRects, TComparer<>.Construct(@CompareFun));

Thaddy:
generics.collections is in Lazarus since at least 3.2.0. The changes over time are fixed compiler bugs.
3.2.4 fixes has one major fix -> constref has become const in generics.collections.
As I wrote, I will add a small example on how to make it compatible;

Thaddy:
Here the example to show difference between Delphi and FPC dynamic array sort:
needs just one line changed between Delphi 12.1 and FPC 3.3.1, possibly 3.2.3 too:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---// sorting dynamic arrays in Freepascal and Delphi{$ifdef fpc}{$mode delphi}{$endif}uses   classes,generics.defaults,generics.collections; type   TARecord = record    min,    max:integer;  end;   TMinComparer = class(TInterfacedObject,IComparer<TARecord>)    function Compare(const Left, Right: TARecord): Integer; overload;  end;   function TMinComparer.Compare(const left,right:TARecord):integer;  begin    result := 0;    if right.min > left.min then result := -1    else if right.min < left.min then result := 1;  end; var  RecordArray:TArray<TARecord> = nil;  MinComparer:IComparer<TARecord>;  R:TARecord;  Idx:nativeint;begin  MinComparer   := TMinComparer.Create;  SetLength(RecordArray,4000);   for idx := 0 to High(RecordArray) do  begin    RecordArray[idx].min := random(40);    RecordArray[idx].max := random(40);  end; {$ifdef fpc}  TArrayHelper<TARecord>.Sort(RecordArray,MinComparer);  // current fpc syntax  {$else delphi}  TArray.Sort<TArecord>(RecordArray,MinComparer); // current delphi syntax  {$endif}  for R in RecordArray do write(R.Min:3);  writeln;  readln;end.It is likely that the  syntax in Delphi mode will later converge: It only needs a rework from TArrayHelper <T> to TArray class, but that is not done yet.
Example adapted from the example I gave elsewhere this week.

Navigation

[0] Message Index

[#] Next page

Go to full version