Thema: TList.Sort

Einzelnen Beitrag anzeigen

Bjoerk

Registriert seit: 28. Feb 2011
Ort: Mannheim
1.384 Beiträge
 
Delphi 10.4 Sydney
 
#7

AW: TList.Sort

  Alt 5. Sep 2011, 22:57
Bist du dir sicher? ich kriegs so nur mit Pointern korrekt sortiert (D2007) !?

Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TItem = record
    AInteger: integer;
  end;
  TItemList = class(TList)
    function GetItem(Index: integer): TItem;
    procedure AddItem(Item: TItem);
    procedure DelItem(Index: integer);
  public
    destructor Destroy; override;
  end;
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TItemList.GetItem(Index: integer): TItem;
var
  PItem: ^TItem;
begin
  PItem:= Items[Index];
  Result:= PItem^;
end;

procedure TItemList.AddItem(Item: TItem);
var
  PItem: ^TItem;
begin
  New(PItem);
  PItem^:= Item;
  Add(PItem);
end;

procedure TItemList.DelItem(Index: integer);
var
  PItem: ^TItem;
begin
  PItem:= Items[Index];
  Dispose(PItem);
  Delete(Index);
end;

destructor TItemList.Destroy;
begin
  while Count > 0 do DelItem(Count-1);
end;

function AIntegerCompare1(Item1, Item2: Pointer): integer; // *** Pointer
begin
  Result:= 0;
  if TItem(Item1^).AInteger > TItem(Item2^).AInteger then
    Result:= 1
  else
    if TItem(Item1^).AInteger < TItem(Item2^).AInteger then
      Result:= -1
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ItemList: TItemList;
  Item: TItem;
  I: integer;
begin
  Randomize;
  ItemList:= TItemList.Create;
  for I:= 1 to 100 do
  begin
    Item.AInteger:= Random(1000);
    ItemList.AddItem(Item);
    ItemList.Sort(AIntegerCompare1);
  end;
  ListBox1.Items.Clear;
  for I:= 0 to ItemList.Count-1 do
    ListBox1.Items.Add(IntToStr(ItemList.GetItem(I).AInteger));
  ItemList.Free;
end;

function AIntegerCompare2(Item1, Item2: TItem): integer; // *** Record
begin
  Result:= 0;
  if Item1.AInteger > Item2.AInteger then
    Result:= 1
  else
    if Item1.AInteger < Item2.AInteger then
      Result:= -1
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  ItemList: TItemList;
  Item: TItem;
  I: integer;
begin
  Randomize;
  ItemList:= TItemList.Create;
  for I:= 1 to 100 do
  begin
    Item.AInteger:= Random(1000);
    ItemList.AddItem(Item);
    ItemList.Sort(@AIntegerCompare2);
  end;
  ListBox1.Items.Clear;
  for I:= 0 to ItemList.Count-1 do
    ListBox1.Items.Add(IntToStr(ItemList.GetItem(I).AInteger));
  ItemList.Free;
end;

end.
  Mit Zitat antworten Zitat