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?
No, in Delphi dynamic arrays are always indexed from zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With