Removing elements from dynamic arrays?
Paul Backus
snarwin at gmail.com
Tue Apr 5 15:43:14 UTC 2022
On Tuesday, 5 April 2022 at 14:10:44 UTC, Steven Schveighoffer
wrote:
> I'd implement it probably like this (for D2):
>
> ```d
> auto drop(T)(ref T[] arr, T which)
> {
> import std.algorithm, std.range;
> auto f = arr.find(which);
> debug if(f.empty) throw ...;
> auto result = arr.front;
> arr = arr.remove(&f[0] - &arr[0]); // god I hate this
> return result;
> }
> ```
I think you can get rid of the ugly pointer arithmetic using
`countUntil`:
```d
auto drop(T)(ref T[] arr, T which)
{
import std.algorithm, std.range, std.exception;
auto i = arr.countUntil(which);
debug enforce(i < arr.length, "Not found");
auto result = arr[i];
arr = arr.remove(i);
return result;
}
```
More information about the Digitalmars-d-learn
mailing list