Pop an element from an array inplace?

bearophile bearophileHUGS at lycos.com
Tue Sep 7 09:50:56 PDT 2010


Paolo Invernizzi:
> What's the best way to find an element into an array, drop it and shrink  
> the array inplace, in D2?

Inside the module std.array there is a commented out function that allows to remove items. I don't know why it is commented out, maybe there is some bug.

You can find the index with the indexOf().
Then if your items don't have a postblit (and you can test for that), then you may just need std.c.string.memmove to shift the items.
If the items are structs with a postblit, then I presume the best thing you can do is to copy each item in a normal loop.
After that "static if", you decrease the array length by 1, and return the item saved in a temporary variable.

------------------------------

Simen kjaeraas:
> T extract( T )( ref T[] haystack, const T element ) {
>      auto loc = indexOf( haystack, element );
>      T result = haystack[loc];
>      haystack = haystack[0..loc] ~ haystack[loc+1..$];
>      return result;
> }

It's not in-place, as requested by Paolo.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list