Removing elements from dynamic arrays?

Salih Dincer salihdb at hotmail.com
Wed Apr 6 03:47:46 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;
> }
> ```

First, you're neglecting the loop.  Second, the returned value is 
the first element of the array. It should be as follows:

```d
auto drop2(T)(ref T[] arr, T which)
{
   //auto f = arr.find(which);
   auto f = arr.find!(a => a == which);

   //debug if(f.empty) throw ...;
   auto result = f.front; // arr.front;

   //arr = arr.remove(&f[0] - &arr[0]);
   arr = remove!(a => a == which)(arr);

   return result;
}
```
We do not know the wishes of the programmer who made the 
development. But it is certain that he scanned until the end of 
the array.  So it doesn't make sense for the resulting output to 
be equal to the ```which```. In summary, one line is enough:

```d
return remove!(a => a == which)(arr);
```
SDB@



More information about the Digitalmars-d-learn mailing list