- Код: Выделить всё
type
TIntegerDynArray = array of integer;
procedure Print(const a: array of integer);
var
v: integer;
begin
for v in a do write(v, ' ');
end;
var
a: TIntegerDynArray;
begin
a := TIntegerDynArray.Create(0, 11, 22, 33, 44, 55);
Print(a[2..4]); // 22, 33, 44
end.
Это означает, что «универсальные» функции, типа сортировки поддиапазона в QSort, можно реализовывать полностью на open array, вместо first: PItem; count: SizeInt:
- Код: Выделить всё
type
Item = integer;
procedure QSort(var a: array of Item);
var
i, j: SizeInt;
avg, t: Item;
begin
if length(a) < 2 then exit;
i := 0;
j := High(a);
avg := a[(i + j) div 2];
repeat
while a[i] < avg do inc(i);
while a[j] > avg do dec(j);
if i <= j then
begin
t := a[i]; a[i] := a[j]; a[j] := t;
inc(i); dec(j);
end;
until i > j;
QSort(a[0 .. j]);
QSort(a[i .. High(a)]);
end;
А если вдруг настанут тяжёлые времена и на руках окажутся только указатель и количество — переинтерпретировать их как массив:
- Код: Выделить всё
type
ItemArray = array[0 .. 0] of Item; PItemArray = ^ItemArray;
var
i, count: SizeInt;
x: ^Item;
begin
count := 100;
x := GetMem(count * sizeof(Item));
try
for i := 0 to count-1 do x[i] := random(100);
QSort(PItemArray(x)^[0 .. count-1]);
for i := 0 to count-2 do Assert(x[i] <= x[i + 1], 'sort failed');
finally
FreeMem(x);
end;
end.