Deleting an element from an array

nobody somebody at somewhere.com
Tue Feb 3 07:36:19 PST 2009


"Frank Benoit" <keinfarbton at googlemail.com> wrote in message 
news:gm9n0e$314n$1 at digitalmars.com...
> nobody schrieb:
>> "Denis Koroskin" <2korden at gmail.com> wrote in message
>> news:op.uor1gzqho7cclz at korden-pc...
>>> On Tue, 03 Feb 2009 15:46:52 +0300, nobody <somebody at somewhere.com> 
>>> wrote:
>>>
>>>> What is the best way to completely remove an element from an array?
>>>>
>>>> For example you have an array:
>>>> [1,2,3,4,5,6]
>>>> and want to remove element "3" in such a way that the resulting array 
>>>> is:
>>>> [1,2,4,5,6]
>>>>
>>>> Thanks.
>>>>
>>>>
>>> import std.array;
>>>
>>> auto arr = [0, 1, 2, 3, 4, 5];
>>>
>>> int lowerBound = 2;
>>> int upperBound = 4;
>>>
>>> // erases elements [lowerBound, upperBound),
>>> // total of upperBound - lowerBound elements
>>> arr.erase(lowerBound, upperBound);
>>>
>>> assert(arr == [0, 1, 4, 5]);
>>>
>>
>> Ah I'm sorry, I forgot to mention I'm using D1, not D2.
>>
>> Thanks for the reply though :)
>>
>>
>
> arr = arr[ 0 .. lowerBound ] ~ arr[ upperBound .. $ ];

Slicing, I always forget it exists..

And wow, I was afraid I would have to do some array length checks in case 
the element to be removed is the last one, but it even works with lowerBound 
= 5 and upperBound = 6.

Splendid, thanks! 




More information about the Digitalmars-d-learn mailing list