Lazarus

Programming => General => Topic started by: Blaazen on August 06, 2012, 07:46:26 pm

Title: How to sort generic list
Post by: Blaazen on August 06, 2012, 07:46:26 pm
Hi,

I have class and generic list:
Code: [Select]
TMyClass =class
  Name: string;
  Count: Integer;
end;

TMyList = specialize TFPGObjectList<TMyClass>;

I would like to Sort by Count, Name or whatever and TFPGObjectList contains public method Sort:
Code: [Select]
procedure Sort(Compare: TCompareFunc);
How and where should I declare its parameter (Compare: TCompareFunc) ?
(Note that TCompareFunc is function returning Integer.)

I'm getting error messages like this:
Quote
umain.pas(425,63) Error: Incompatible type for arg no. 1: Got "<procedure variable type of function(const TMyClass;const TMyClass):LongInt of object;Register>", expected "TFPGObjectList$1$crc7683A43D.<procedure variable type of function(const TMyClass;const TMyClass):LongInt;Register>"
Title: Re: How to sort generic list
Post by: Leledumbo on August 06, 2012, 07:58:06 pm
Quote
How and where should I declare its parameter (Compare: TCompareFunc) ?
(Note that TCompareFunc is function returning Integer.)
Anywhere as long as it's part of an object (e.g. a method). I usually create a descendant class containing this Compare method and overload the Sort method (or create a new one with clearer names like SortByCount, SortByName, etc) with no parameter which calls that original Sort method with the specified Compare method.
Title: Re: How to sort generic list
Post by: Blaazen on August 06, 2012, 09:22:41 pm
OK, I have class:

Code: [Select]
TMyList = class(specialize TFPGObjectList<TMyClass>)
  procedure Sort(Compare: TCompareFunc);
  function SortNameAsc(const A1,A2:TMyClass): Integer;
end;
and
Code: [Select]
procedure TMyList.Sort(Compare: TCompareFunc);
begin
  inherited Sort(@SortBWNameAsc);
end;

I'm still getting the same error.
Title: Re: How to sort generic list
Post by: eny on August 06, 2012, 09:59:52 pm
The compare function doesn't look like a method function but a plain old pascal function.
So I guess you'll have to do something like:
Code: [Select]
function CompareNameAsc(const Item1, Item2: TMyClass): Integer;
begin
  // Do comparison for -1, 0, 1
end;

{ TMyList }

procedure TMyList.SortByName;
begin
  Sort(@CompareNameAsc);
end;
The benefit is that you can now add a typed compare function instead of the untyped one where you had to do a typecast for comparison.
Title: Re: How to sort generic list
Post by: Blaazen on August 06, 2012, 10:22:41 pm
@ The compare function doesn't look like a method function but a plain old pascal function.

Thanks, that was it.
Title: Re: How to sort generic list
Post by: Leledumbo on August 06, 2012, 11:44:54 pm
Oops, sorry. I misinterpret the error message.
TinyPortal © 2005-2018