Arrays - Inserting and moving data

Timon Gehr timon.gehr at gmx.ch
Thu Feb 9 11:49:43 PST 2012


On 02/09/2012 08:20 PM, MattCodr wrote:
> On Thursday, 9 February 2012 at 18:30:22 UTC, Ali Çehreli wrote:
>> On 02/09/2012 03:47 AM, MattCodr wrote:
>>> 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.
>>
>> Most straightforward that I know of is the following:
>>
>> arr = arr[0 .. position] ~ [ newValue ] ~ arr[position + 1 .. $];
>>
>> But if you don't actually want to modify the data, you can merely
>> access the elements in-place by std.range.chain:
>>
>> import std.stdio;
>> import std.range;
>>
>> void main()
>> {
>> int[] arr = [0,1,2,3,4,5,6,7,8,9];
>> immutable position = arr.length / 2;
>> immutable newValue = 42;
>>
>> auto r = chain(arr[0 .. position], [ newValue ], arr[position + 1 .. $]);
>> writeln(r);
>> }
>>
>> 'r' above is a lazy range that just provides access to the three
>> ranges given to it. 'arr' does not change in any way.
>>
>> Ali
>
> Hi Ali,
>
> You gave me a tip with this "chain" feature.
>
> I changed a few lines of your code, and it worked as I wanted:
>
>
> import std.stdio;
> import std.range;
> import std.array;
>
> void main()
> {
> int[] arr = [0,1,2,3,4,5,6,7,8,9];
> immutable position = arr.length / 2;
> immutable newValue = 42;
>
> auto r = chain(arr[0 .. position], [ newValue ], arr[position .. $-1]);
> arr = array(r);
>
> foreach(int i; arr)
> writefln("%d", i);
> }
>
>
> Thanks,
>
> Matheus.
>

Note that this code does the same, but is more efficient if you don't 
actually need the array:


import std.stdio;
import std.range;
import std.array;

void main()
{
     int[] arr = [0,1,2,3,4,5,6,7,8,9];
     immutable position = arr.length / 2;
     immutable newValue = 42;

     auto r = chain(arr[0 .. position], [ newValue ], arr[position .. $-1]);

     foreach(i; r)
         writefln("%d", i);
}






More information about the Digitalmars-d-learn mailing list