Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

A Simple Way to Delete an Element from a Dynamic Array

Title: A Simple Way to Delete an Element from a Dynamic Array Question: How to delete an element from a dynamic array without using pointers Answer: I have searched for an answer to this question, and I haven't found an answer... Maybe I wasn't too persistent, or maybe I didn't ask the right question... I don't know if this solution is the fastest but it's simple. Here is the idea: type TSomeArray = array of TSomeType;//you can replace TSomeType with wherever... //...you want var table : TSomeArray; //our dynamic array procedure DeleteElement(var anArray:TSomeArray; const aPosition:integer); var lg, j : integer; begin lg := length(anArray); if aPosition lg-1 then exit else if aPosition = lg-1 then begin //if is the last element //if TSomeType is a TObject descendant don't forget to free it //for example anArray[aPosition].free; Setlength(anArray, lg -1); exit; end; for j := aPosition to lg-2 do//we move all elements from aPosition+1 left... anArray[j] := anArray[j+1];//...with a position SetLength(anArray, lg-1);//now we have one element less //that's all... end; //Here is how you can use it procedure TForm1.Button1Click(Sender : TObject); begin DeleteElement(table,1);//we suppose that "table" has been filled previously end;