D idom for removing array elements

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 30 04:50:06 PST 2017


On 01/30/2017 01:33 PM, albert-j wrote:
> On Monday, 30 January 2017 at 12:31:33 UTC, albert-j wrote:
>
>>
>> OK, got it. Can you do removal without reallocation with
>> std.container.array?
>>
>>     Array!int arr;
>>     foreach (i; 0..10) arr ~= i;
>
> Sorry, sent too early.
>
>     arr = arr[].remove!(x=> x > 5); //Doesn't work withouth calling
> .Array!int

Looks like it can't be done in that straight-forward manner. But you can 
do the `remove` and then update just `arr`'s length:

----
void main()
{
     import std.container: Array;
     import std.algorithm: equal, remove;

     Array!int arr;
     foreach (i; 0..10) arr ~= i;
     const oldAddress = &arr[0];

     arr.length = arr[].remove!(x=> x > 5).length;

     assert(equal(arr[], [0, 1, 2, 3, 4, 5])); /* holds */
     assert(&arr[0] is oldAddress); /* holds */
}
----

Maybe std.container.Array can be improved somehow to simplify this. But 
I'm not sure about the details.


More information about the Digitalmars-d-learn mailing list