Thread overview
Pop an element from an array inplace?
Sep 07, 2010
Paolo Invernizzi
Sep 07, 2010
Simen kjaeraas
Sep 07, 2010
bearophile
September 07, 2010
Hi all,

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

Thanks in advance, Paolo
September 07, 2010
Paolo Invernizzi <paolo.invernizzi@srlabs.it> wrote:

> Hi all,
>
> What's the best way to find an element into an array, drop it and shrink the array inplace, in D2?
>
> Thanks in advance, Paolo

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;
}

Not tested, but should work.

-- 
Simen
September 07, 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