Remove array element within function

Mike Parker aldacron at gmail.com
Mon Jul 5 14:30:11 UTC 2021


On Monday, 5 July 2021 at 13:34:50 UTC, Rekel wrote:
> Ah, ref, thanks, I didn't know if that would work as I was 
> confused since arrays themselves are kind of already pointers.

Except they're not :-) Think of them as struct instances with 
length and pointer fields. That's actually what they are.


>
> I believe for setting length it was both when I wanted to 
> initialize the array to a certain length (instead of having 
> that inline with the declaration)

```d
int[] arr;
arr = new int[](100);
```

> & when I want to clear the array of all data. Though I also 
> found threads in which people mentioned changing the length 
> manually after calling remove.

You shouldn't need to adjust the length after remove as long as 
you assign the return value to the original array. And actually, 
I didn't pay close enough attention to your original function. 
You didn't do that. It should be:

```d
void removeItem(ref int[] a){
     ...
     a = a.remove(index);
}
```

Or this:

```d
int[] removeElement(int[] a) {
     ...
     return a.remove(index);
}

// Later
elems = removeElement(elems);
```

> The copies were mostly at play in scenarios such as this one, 
> but also when I'm appending lists to lists, in a 
> `list.addAll(list2);` scenario. Though I guess I'm just not 
> used to reassigning on the list variable after doing things 
> with it.

You never copy the contents of a dynamic array/slice. That only 
comes into play with static arrays:

```d
void someFunc1(int[3] a) {}
void someFunc2(int[] a);

int[3] a = [1, 2, 3];
someFunc1(a);    // This copies all the elements
someFunc2(a);    // This implicitly slices the array
```

Here are some resources that may help:

https://ddili.org/ders/d.en/arrays.html
https://ddili.org/ders/d.en/slices.html
https://dlang.org/articles/d-array-article.html
https://dlang.org/blog/2017/03/20/dont-fear-the-reaper/

Pay particular attention to the append operator + reserve. That 
plus the ability to slice without copying is where the real power 
of D's arrays lies. Then look into `std.array.Appender` when you 
have lots of items to append:

https://dlang.org/phobos/std_array.html#Appender

>
> Also, is my use of long correct? The documentation wasn't very 
> clear on the return type of remove, just calling it a 'number'.

If you look in the function signature, it returns `ptrdiff_t`:

https://dlang.org/phobos/std_algorithm_searching.html#countUntil

Which is defined in `object.d`:

https://github.com/dlang/druntime/blob/master/src/object.d#L61

It's `long` on 64-bit systems and `int` on 32-bit. So you can use 
`ptrdiff_t` or just `auto`:

```d
auto index = countUntil(...);
```

>
> Again thanks for your help 😅

That's why we're here :-)



More information about the Digitalmars-d-learn mailing list