array.remove(int), similar to aa.remove(key)

Oskar Linde oskar.lindeREM at OVEgmail.com
Wed May 24 02:14:13 PDT 2006


Ough, some mistakes.

Oskar Linde skrev:
> Lionello Lunesu skrev:
>> array.remove(int) could simply replace [i] with [$-1] and decrement 
>> the length.
>>
>> I need this quite a lot and it gets tiresome writing the same 'for' 
>> over and over. Furthermore, like I've mentioned in the title: since 
>> AA's have it, it makes sense to add it to normal arrays as well.
> 
> Since arrays are ordered, it is not clear that array.remove(int) should be
> 
> array[i] = array[$-1], array.length = array.length -1;
> 
> rather than:
> 
> array = array[0..$i-1] ~ array[i+1..$];

$i is a typo, should be i.

> 
> 
> Note: if you want to implement array.remove(int) by yourself, it is 
> trivial (untested code):
> 
> template remove(ArrTy, IntTy) {
>     static assert(is(IntTy : int));
>     void remove(ArrTy arr, IntTy ix) {
>         arr[ix] = arr[$-1];
>         arr.length = arr.length - 1;
>     }
> }
> 
> and use it such as:
> 
> char[] t = "abc".dup;
> assert(t.remove(1) == "ac");

The template function above doesn't return anything, so this should of 
course be:

char[] t = "abc".dup;
t.remove(1);
assert(t == "ac");

/Oskar



More information about the Digitalmars-d mailing list