Arrays - Inserting and moving data

Pedro Lacerda pslacerda at gmail.com
Thu Feb 9 04:50:39 PST 2012


I __believe__ that insertInPlace doesn't shift the elements, but use an
appender allocating another array instead.
Maybe this function do what you want.


    int[] arr = [0,1,2,3,4,5,6,7,8,9];

    void maybe(T)(T[] arr, size_t pos, T value) {
        size_t i;
        for (i = arr.length - 1; i > pos; i--) {
            arr[i] = arr[i-1];
        }
        arr[i] = value;
    }

    maybe(arr, 3, 0);
    maybe(arr, 0, 1);
    assert(arr == [1, 0, 1, 2, 0, 3, 4, 5, 6, 7]);



2012/2/9 MattCodr <matheus_nab at hotmail.com>

> I have a doubt about the best way to insert and move (not replace) some
> data on an array.
>
> For example,
>
> In some cases if I want to do action above, I do a loop moving the data
> until the point that I want and finally I insert the new data there.
>
>
> In D I did this:
>
> begin code
> .
> .
> .
>   int[] arr = [0,1,2,3,4,5,6,7,8,9];
>
>   arr.insertInPlace(position, newValue);
>   arr.popBack();
> .
> .
> .
> end code
>
>
> After the insertInPlace my array changed it's length to 11, so I use
> arr.popBack(); to keep the array length = 10;
>
> The code above is working well, I just want know if is there a better way?
>
> Thanks,
>
> Matheus.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20120209/b26b548a/attachment.html>


More information about the Digitalmars-d-learn mailing list