Einzelnen Beitrag anzeigen

Bjoerk

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

AW: interne Funktionsweise eines Arrays

  Alt 19. Jul 2014, 17:35
Gut. Dann würd' ich satt des Array aber ein kleine Klasse schreiben? Beispiel:

Delphi-Quellcode:
  TIntegerList = class
  private
    FCount, FCapacity: integer;
    FItems: array of integer;
    function GetItems(Index: integer): integer;
    procedure SetItems(Index: integer; const Value: integer);
    function DeltaCapacity: integer;
    procedure SetCapacity(const Value: integer);
  public
    function Add(const Value: integer): integer;
    procedure Insert(const Index: integer; const Value: integer);
    procedure Delete(const Index: integer);
    procedure Clear;
    property Items[Index: integer]: integer read GetItems write SetItems; default;
    property Count: integer read FCount;
    property Capacity: integer read FCapacity write SetCapacity;
    destructor Destroy; override;
  end;

{ TIntegerList }

destructor TIntegerList.Destroy;
begin
  Clear;
  inherited Destroy;
end;

procedure TIntegerList.Clear;
begin
  SetCapacity(0);
  FCount := 0;
end;

function TIntegerList.DeltaCapacity: integer;
begin
  if FCapacity > 64 then
    Result := FCapacity div 4
  else
    if FCapacity > 8 then
      Result := 16
    else
      Result := 4;
end;

procedure TIntegerList.SetCapacity(const Value: integer);
begin
  FCapacity := Value;
  SetLength(FItems, FCapacity);
end;

function TIntegerList.Add(const Value: integer): integer;
begin
  Result := FCount;
  Insert(Result, Value);
end;

procedure TIntegerList.Insert(const Index: integer; const Value: integer);
var
  I: integer;
begin
  if (Index >= 0) and (Index <= FCount) then
  begin
    if FCount = FCapacity then
      SetCapacity(FCapacity + DeltaCapacity);
    Inc(FCount);
    for I := FCount - 1 downto Index + 1 do
      FItems[I] := FItems[I - 1];
    FItems[Index] := Value;
  end;
end;

procedure TIntegerList.Delete(const Index: integer);
var
  I: integer;
begin
  if (Index >= 0) and (Index < FCount) then
  begin
    for I := Index to FCount - 2 do
      FItems[I] := FItems[I + 1];
    Dec(FCount);
    FItems[FCount] := 0;
  end;
end;

function TIntegerList.GetItems(Index: integer): integer;
begin
  Result := FItems[Index];
end;

procedure TIntegerList.SetItems(Index: integer; const Value: integer);
begin
  FItems[Index] := Value;
end;
  Mit Zitat antworten Zitat