Recent

Author Topic: Passing a record field as procedure argument  (Read 796 times)

Badger

  • Full Member
  • ***
  • Posts: 144
Passing a record field as procedure argument
« on: January 18, 2020, 06:17:50 am »
Is it possible to pass a  record field as a procedure argument? For example, if you have an array of 'StudentRecords' with elements 'Name', 'Age', 'Height', Marks etc, can you sort the records by using -  Procedure SortTheArray(NominatedArray:Array; SelectedArraySortField:Field of Array), so that you could sort any array by any of its fields - (Name, Age, Height etc in this case).

Not sure if "Array" by itself would work but if you used Array of StudentRecords, it would limit the scope of the array that could be processed.  I can't figure how to nominate the SelectedArraySortField part.  Any suggestions?
« Last Edit: January 18, 2020, 06:31:54 am by Badger »
Badger
(A bad tempered, grumpy animal that sleeps most of the winter!)

If at first you don't succeed - you're running about average!

I'm using Windows 10 Lazarus v2.4.4  FPC 3.2.2   Win 32/64

avk

  • Hero Member
  • *****
  • Posts: 752
Re: Passing a record field as procedure argument
« Reply #1 on: January 18, 2020, 07:54:32 am »
For example, assuming you have a QSort procedure that accepts an array and a comparator:
Code: Pascal  [Select][+][-]
  1. ...
  2. type
  3.  
  4.   TStudent = record
  5.     Name: string;
  6.     Age: Word;
  7.     Height: Single;
  8.   end;
  9.  
  10.   TStudentField = (sfName, sfAge, sfHeight);
  11.   TStudentLess  = function(const L, R: TStudent): Boolean;
  12.  
  13.   function NameLess(const L, R: TStudent): Boolean;
  14.   function AgeLess(const L, R: TStudent): Boolean;
  15.   function HeightLess(const L, R: TStudent): Boolean;
  16.   procedure Sort(var a: array of TStudent; aField: TStudentField);
  17.  
  18. const
  19.   Comparators: array[TStudentField] of TStudentLess = (@NameLess, @AgeLess, @HeightLess);
  20.  
  21. implementation
  22.  
  23. function NameLess(const L, R: TStudent): Boolean;
  24. begin
  25.   Result := L.Name < R.Name;
  26. end;
  27.  
  28. function AgeLess(const L, R: TStudent): Boolean;
  29. begin
  30.   Result := L.Age < R.Age;
  31. end;
  32.  
  33. function HeightLess(const L, R: TStudent): Boolean;
  34. begin
  35.   Result := L.Height < R.Height;
  36. end;
  37.  
  38. procedure Sort(var a: array of TStudent; aField: TStudentField);
  39. begin
  40.   QSort(a, Comparators[aField]);
  41. end;
  42. ...
  43.  

 

TinyPortal © 2005-2018