On 30 Jun 1997 20:47:30 GMT, Edward Theunissen
Quote
<Edward.Theunis...@tip.nl> wrote:
>I try to use a Compare-function to sort an instance of a TList object,
>however without succes. An example of this, for a Delphi 2.0 application, with
>all the necessary type, Var and funtion declarations would help me lot.
>Thanks,
>Edward Theunissen.
The help files are very short, almost cryptical, when explaining this
method. Doing something wrong makes the application crash, leaving very
little clue of what to look for. An example in the help file, or at
least a TI-article on the Borland web would have helped a lot.
Anyhow, here it goes:
The Sort method requires you to write your function, since the TList
object cannot know what kind of objects which are stored in it (it just
holds the pointers). The function must be of type TListSortCompare (but
do not focus on the type class, you only have to use the declaration).
In the example below we assume that we declared a TList-object which we
use for storing doubles.
Further, the function must compare Item1 and Item2 (see declaration), it
must return -1 if Item1 is less than Item2, 1 if Item1 is greater than
Item2, AND it must return 0 if they are equal. DON'T omit the last one,
this makes the application crash, since the sorting is based on a
quicksort.
Type
TForm1 = class(TForm)
{snip bla, bla}
end;
PDouble : ^Double;
function Compare(Item1, Item2: Pointer): Integer;
var
Mylist: Tlist;
implementation
{Some Procedure Adding values to the list - unsorted}
Var
DP: PDouble; //Pointer
Begin
{some kind of statements that will be repeated,
this is just an example, it can be done in many ways}
New(DP); //DP is a pointer to a double
DP^ := StrToFloat(Edit1.Text); //put a floating point value in to it
SOListe.Add(DP); //add it to the list
end;
function compare(Item1, Item2: Pointer): Integer; //YOUR function
{The function may look like this.
Keep as simple as possible, remember this one will be
run a lot of times during a sort.}
begin
if Double(Item1^) < Double(Item2^) then result := -1
Else if Double(Item1^) > Double(Item2^) then result := 1
Else result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
{When you have got the function right, sorting is easy}
Begin
MyList.Sort(Compare); //Use Function as argument
end;
--
Geir
--
Geir Tutturen
geir.tuttu...@itf.nlh.no
(use this address (the return address is a spam avoiding fake))