array.remove(int), similar to aa.remove(key)
Lionello Lunesu
lio at lunesu.remove.com
Wed May 24 04:31:55 PDT 2006
Oskar Linde wrote:
> 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..$];
OK, so there could be two removes, ordered and unordered.
> 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;
> }
> }
That's what I did, and it's the code I end up coding/copy-pasting
whenever I need it. Nice touch though, that static assert.
L.
More information about the Digitalmars-d
mailing list