動的配列の指定された要素を削除する方法-Splendourの質問の一部に返信します.
1965 ワード
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;