2009. június 24., szerda

Create a sorted TList that holds integers


Problem/Question/Abstract:

How can I create a TStringlist cousin which holds integers rather than strings. I need the ability to keep a list of objects sorted by an integer with full binary IndexOf.

Answer:

Use a TList, and do casts where appropriate:

To write:

MyList.Add(Pointer(17));
MyList.Add(Pointer(39));

To read:

MyInt := Integer(MyList[0]);

To sort:

procedure CompareInts(Item1, Item2: Pointer): Integer;
begin
  if Integer(Item1) > Integer(Item2) then
    Result := 1
  else if if Integer(Item1) < Integer(Item2) then
    Result := -1
  else
    Result := 0;
end;
{ ... }
MyList.Sort(CompareInts);

Nincsenek megjegyzések:

Megjegyzés küldése