Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi SetLength Custom Indexing

In Delphi, it is possible to create an array of the type

var
  Arr: array[2..N] of MyType;

which is an array of N - 1 elements indexed from 2 to N.

If we instead declare a dynamic array

var
  Arr: array of MyType

and later allocate N - 1 elements by means of

SetLength(Arr, N - 1)

then the elements will be indexed from 0 to N - 2. Is it possible to make them indexed from 2 to N (say) instead?

like image 324
Andreas Rejbrand Avatar asked May 01 '10 13:05

Andreas Rejbrand


2 Answers

No, in Delphi dynamic arrays are always indexed from zero.

like image 178
vcldeveloper Avatar answered Nov 20 '22 11:11

vcldeveloper


YES! By using a trick!
First declare a new type. I use a record type instead of a class since records are a bit easier to use.

type
  TMyArray = record
  strict private
    FArray: array of Integer;
    FMin, FMax:Integer;
    function GetItem(Index: Integer): Integer;
    procedure SetItem(Index: Integer; const Value: Integer);
  public
    constructor Create(Min, Max: integer);
    property Item[Index: Integer]: Integer read GetItem write SetItem; Default;
    property Min: Integer read FMin;
    property Max: Integer read FMax;
  end;

With the recordtype defined, you now need to implement a bit of code:

constructor TMyArray.Create(Min, Max: integer);
begin
  FMin := Min;
  FMax := Max;
  SetLength(FArray, Max + 1 - Min);
end;

function TMyArray.GetItem(Index: Integer): Integer;
begin
  Result := FArray[Index - FMin];
end;

procedure TMyArray.SetItem(Index: Integer; const Value: Integer);
begin
  FArray[Index - FMin] := Value;
end;

With the type declared, you can now start to use it:

var
  Arr: TMyArray;
begin
  Arr := TMyArray.Create(2, 10);
  Arr[2] := 10;

It's actually a simple trick to create arrays with a specific range and you can make it more flexible if you like. Or convert it to a class. Personally, I just prefer records for these kinds of simple types.

like image 1
Wim ten Brink Avatar answered Nov 20 '22 10:11

Wim ten Brink