type
TArr = array of TPoint; {把數組先定義成一個類型會方便許多, 這裡僅用 TPoint 測試}
{刪除動態數組指定元素的過程: 參數 arr 是數組名, 參數 Index 是要刪除的索引}
procedure DeleteArrItem(var arr: TArr; Index: Integer);
var
Count: Cardinal;
begin
Count := Length(arr);
if (Count = 0) or (Index < 0) or (Index >= Count) then Exit;
Move(arr[Index+1], arr[Index], (Count-Index)* SizeOf(arr[0]));
SetLength(arr, Count - 1);
end;
{測試}
procedure TForm1.Button1Click(Sender: TObject);
var
arr: TArr;
i: Integer;
begin
{測試數據}
SetLength(arr, 5);
arr[0].X := 1; arr[0].Y := 111;
arr[1].X := 2; arr[1].Y := 222;
arr[2].X := 3; arr[2].Y := 333;
arr[3].X := 4; arr[3].Y := 444;
arr[4].X := 5; arr[4].Y := 555;
{刪除第四個元素, 並查看刪除後的結果}
DeleteArrItem(arr, 3);
for i := 0 to Length(arr) - 1 do
Memo1.Lines.Add(Format('%d, %d', [arr[i].X, arr[i].Y]));
end;
有時使用動態數組的指針更方便, 簡單修改即可:
type
TArr = array of TPoint;
PArr = ^TArr;
{過程}
procedure DeleteArrItem(p: PArr; Index: Integer);
var
Count: Cardinal;
begin
Count := Length(p^);
if (Count = 0) or (Index < 0) or (Index >= Count) then Exit;
Move(p^[Index+1], p^[Index], (Count-Index)* SizeOf(p^[0]));
SetLength(p^, Count - 1);
end;
{測試}
procedure TForm1.Button1Click(Sender: TObject);
var
arr: TArr;
i: Integer;
begin
SetLength(arr, 5);
arr[0].X := 1; arr[0].Y := 111;
arr[1].X := 2; arr[1].Y := 222;
arr[2].X := 3; arr[2].Y := 333;
arr[3].X := 4; arr[3].Y := 444;
arr[4].X := 5; arr[4].Y := 555;
DeleteArrItem(@arr, 3);
for i := 0 to Length(arr) - 1 do
Memo1.Lines.Add(Format('%d, %d', [arr[i].X, arr[i].Y]));
end;