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

Oskar Linde oskar.lindeREM at OVEgmail.com
Wed May 24 02:04:35 PDT 2006


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..$];


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");

Regards,

Oskar



More information about the Digitalmars-d mailing list