How to use the method Sort of the class TList in Delphi

sorting delphi tlist

354 观看

1回复

11 作者的声誉

How does the method Sort of the class TList work? Does this method only sort in a way that the elements of the list only ascend/descend? Please, have a look at the code below.

Type 
  PInteger = ^Integer;
Function Compare(Item1, Item2 : Pointer) : Integer;
Begin
 if PInteger(Item1)^ > Pinteger(Item2)^ then Result:= 1
 else if PInteger(Item1)^ < PInteger(Item2)^ then Result:= -1
 else Result:= 0;

End;
 { And, for instance, somewhere we call the method }
 List.Sort(Compare);

Now the thing is, after i compile the code, it works well, the list is sorted in a way that the elements ascend. But i don't understand the following line:

PInteger(item1)^ // What does this represent?

And what item1, item2 pointers point to? Do they not need to be initialized?

作者: Arthur Hmayakyan 的来源 发布者: 2017 年 12 月 27 日

回应 1


3

1732 作者的声誉

First what PInteger(item1)^ does/represent?

  1. Item1 is a Pointer, the address of an item stored in the TPointerList.
  2. PInteger is a typed pointer, this means that this pointer points to an address where it is expected to find an integer (four bytes).
  3. ^ the dereferencing symbol, you can use this with pointers to tell the compiler that you want to use the data stored in the address that the pointer is currently pointing to
  4. PInteger(item1)^ you are performing a typecast. in other words you are telling the compiler to treat the pointer Item1 as if it was PInteger then you dereference it to use its data/value stored at the address Item1

Now back to your code. Your function expects two pointers to Items (Integers) from the list which then you compare the data stored in those address (by dereferencing). This means that the list is responsible for the pointers given to your function, in fact if the ItemCount is less than 1 your function will not be executed.

Note: you need to understand that this function will fail if the pointers are pointing to something other than integers (or give an undefined behavior).

作者: Nasreddine Galfout 发布者: 2017 年 12 月 27 日
32x32