Removing elements from dynamic arrays?
Enjoys Math
enjoysmath at gmail.com
Mon Apr 4 23:15:30 UTC 2022
https://forum.dlang.org/post/eih04u$1463$1@digitaldaemon.com
A version of the code that takes `T which` as a parameter instead
of `int index`.
```
// remove an item from an array
template drop(T)
{
T drop( inout T[] arr, T which )
{
int i;
T result;
for (i=0; i < arr.length; i++)
{
if (arr[i] == which)
{
result = arr[i];
break;
}
}
debug if ( which >= arr.length)
throw new Exception(str.format("Attempt to drop the %s of
value %s from an array, but it was not found.", typeid(T),
which));
}
for (; i < arr.length; i++)
{
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;
return result;
}
}
```
It has worse case complexity O(2n) = O(n) whereas the other one
can run in half as long minimally and sometimes just as long (but
still O(n)), but usually one needs to linear search for the entry
first.
More information about the Digitalmars-d-learn
mailing list