Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending one element to a dynamic array

Tags:

delphi

This is a very frequent pattern throughout my code:

SetLength(SomeDynamicArray, Length(SomeDynamicArray)+1);
SomeDynamicArray[High(SomeDynamicArray)] := NewElement;

Is there no way to do this in one line?

Edit: This is incredibly inefficient. I know. I use dynamic arrays (in my own code, in my personal projects which only I use) foremost because they are the easiest to use, and I just need to get things done with as little code as possible.

like image 509
Vladimir Panteleev Avatar asked Apr 22 '11 13:04

Vladimir Panteleev


People also ask

How do you add a value to an array dynamically?

Since the size of an array is fixed you cannot add elements to it dynamically. But, if you still want to do it then, Convert the array to ArrayList object. Add the required element to the array list.

How can we append one dynamic array to another?

Create a dynamic array of int with a initial space of 4. Write a function 'append' that appends a given value to this array. At any stage, if this function finds the array full it automatically doubles the size of array to accommodate this new value. Also write a function to display all the elements of this array.

How do you dynamically add an element to an array in typescript?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.

What is the time complexity of adding an element into a dynamic array that is already filled?

Explanation: In general, the time complexity of inserting or deleting elements at the end of dynamic array is O (1). Elements are added at reserved space of dynamic array. If this reserved space is exceeded, then the physical size of the dynamic array is reallocated and every element is copied from original array.


1 Answers

Here's a hack with generics which only works with TArray<T>:

type
  TAppender<T> = class
    class procedure Append(var Arr: TArray<T>; Value: T);
  end;

class procedure TAppender<T>.Append;
begin
  SetLength(Arr, Length(Arr)+1);
  Arr[High(Arr)] := Value;
end;

Usage:

var
  TestArray: TArray<Integer>;

begin
  TAppender<Integer>.Append(TestArray, 5);
end.
like image 170
Vladimir Panteleev Avatar answered Sep 21 '22 08:09

Vladimir Panteleev