随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253


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;

posted on 2010-04-12 11:37  万一  阅读(...)  评论(...编辑  收藏