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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With