Recent

Author Topic: Sort Comparer function  (Read 1549 times)

jcmontherock

  • Full Member
  • ***
  • Posts: 140
Re: Sort Comparer function
« Reply #15 on: August 05, 2022, 09:26:54 pm »
How do you pass to a new record without getmem/freemem or new/dispose and save address of each in a TList ?

MarkMLl

  • Hero Member
  • *****
  • Posts: 5127
Re: Sort Comparer function
« Reply #16 on: August 05, 2022, 10:30:38 pm »
Use a class instead of a record, create it (either with parameters defining the content or by setting them via properties) and then pass that to the list's add method.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

Thausand

  • Sr. Member
  • ****
  • Posts: 291
Re: Sort Comparer function
« Reply #17 on: August 08, 2022, 07:58:46 pm »
How do you pass to a new record without getmem/freemem or new/dispose and save address of each in a TList ?
I not sure if understand correct.

If want new record then getmem/new is need. No need getmem/new when use static record.

Code: Pascal  [Select][+][-]
  1. program static;
  2.  
  3. {$mode objfpc}
  4.  
  5. uses
  6.   classes,sysutils;
  7.  
  8. type
  9.   PStaticRecord=^TStaticRecord;
  10.   TStaticRecord=record
  11.     Field1:string;
  12.     Field2:integer;
  13.   end;
  14.  
  15. var
  16.   StaticRecordList:TList;
  17.   StaticRecords:array of TStaticRecord=
  18.   ((field1:'one';field2:1),
  19.    (field1:'two';field2:2),
  20.    (field1:'three';field2:3),
  21.    (field1:'four';field2:4),
  22.    (field1:'five';field2:5),
  23.    (field1:'six';field2:6),
  24.    (field1:'seven';field2:7),
  25.    (field1:'eight';field2:8),
  26.    (field1:'nine';field2:9),
  27.    (field1:'ten';field2:10));
  28.  
  29. function SortListCompare(item1,item2:pointer):integer;
  30. begin
  31.   result:=CompareText(PStaticRecord(item1)^.Field1,PStaticRecord(item2)^.Field1);
  32. end;
  33.  
  34. var
  35.   index:integer;
  36.   StaticRecord:PStaticRecord;
  37.  
  38. begin
  39.   StaticRecordList:=TList.Create;
  40.  
  41.   for index:=Low(StaticRecords) to High(StaticRecords)
  42.     // Addr = @
  43.     do StaticRecordList.Add(Addr(StaticRecords[index]));
  44.  
  45.   // write
  46.   writeln;
  47.   for StaticRecord in StaticRecordList
  48.     do Writeln(StaticRecord^.field1:6,' ',StaticRecord^.Field2:2);
  49.  
  50.   // sort
  51.   StaticRecordList.Sort(@SortListCompare);
  52.  
  53.   // write
  54.   writeln;
  55.   for StaticRecord in StaticRecordList
  56.     do Writeln(StaticRecord^.field1:6,' ',StaticRecord^.Field2:2);
  57.  
  58.   StaticRecordList.Free;
  59. end.
  60.  

 

TinyPortal © 2005-2018