DeleteRange<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class procedure DeleteRange<T>(var A: TArray<T>;
  AStartIndex, AEndIndex: Integer);
  overload; static;

class procedure DeleteRange<T>(var A: TArray<T>; AStartIndex: Integer);
  overload; static;

Description

Deletes a range of one or more elements from an array.

The length of the array is reduced by the number of elements deleted.

Parameters:

Note

If you want to delete all the elements of an array with indices ≥ AStartIndex then there is no need to provide AEndIndex.

To delete a single element set both AStartIndex and AEndIndex to the same index. Alternatively use Delete<T>.

Example

Example #1

This first example deletes a range of values from the start, the middle and the end of an array.

procedure DeleteRange_Eg1;
var
  A, B, Expected: TArray<Integer>;
begin
  // We have to copy B to get round an obscure Delphi bug that seems to optimise
  // multiple TArray<Integer>.Create calls for the same elements.
  B := TArray<Integer>.Create(1, 2, 3, 4, 5);

  // delete 1st three elements
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, 0, 2);
  Expected := TArray<Integer>.Create(4, 5);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));

  // delete 3 elements from index 1
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, 1, 3);
  Expected := TArray<Integer>.Create(1, 5);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));

  // delete last 3 elements
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, 2);
  // last index not required: if provided provided Pred(Length(A))
  Expected := TArray<Integer>.Create(1, 2);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));
end;

Example #2

In the second example we a try DeleteRange<T> with start and end indexes outside the bounds of the array.

procedure DeleteRange_Eg2;
var
  A, B, Expected: TArray<Integer>;
begin
  // We have to copy B to get round an obscure Delphi bug that seems to optimise
  // repeated TArray<Integer>.Create calls for the same elements.
  B := TArray<Integer>.Create(1, 2, 3, 4, 5);
  // delete from start to index 2, providing negative start index
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, -3, 2);
  Expected := TArray<Integer>.Create(4, 5);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));

  // delete from index 2 to end of array, providing a very large end index
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, 2, 42);
  Expected := TArray<Integer>.Create(1, 2);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));

  // delete nothing because start index > end index
  A := Copy(B);
  TArrayUtils.DeleteRange<Integer>(A, 3, 2);
  Expected := TArray<Integer>.Create(1, 2, 3, 4, 5);
  Assert(TArrayUtils.Equal<Integer>(Expected, A));
end;

See Also