Using zip to copy subarray into another

Craig Dillabaugh cdillaba at cg.scs.carleton.ca
Wed Aug 14 07:16:08 PDT 2013


On Tuesday, 13 August 2013 at 21:10:53 UTC, John Colvin wrote:
> On Tuesday, 13 August 2013 at 20:23:00 UTC, Craig Dillabaugh 
> wrote:
>> On Tuesday, 13 August 2013 at 19:50:37 UTC, Jonathan M Davis
>> wrote:
>>> On Tuesday, August 13, 2013 21:22:24 Craig Dillabaugh wrote:
>>>> I have code that attempts to copy a slice of one array into
>>>> another using zip. However, the array is not updated. I am
>>>> guessing this is because modifying the returned tuple does 
>>>> not
>>>> modify the actual arrays.
>>>> 
>>>> Is there any way to do this.
>>>
>>> Why not just use std.algorithm.copy, or even just assigning 
>>> one array to the
>>> other? e.g.
>>>
>>> dest[2 .. 5] = src[1 .. 4];
>>>
>>> - Jonathan M Davis
>>
>> These work reasonably well and I will likely use your 
>> suggestions
>> here.
>>
>> The one thing I get with zip that I lose using 
>> std.algorithm.copy
>> or straight assignment of the slices is that it handles
>> mismatches in slice sizes automatically (it stops as soon as
>> either slice is exhausted).
>>
>> For example
>>
>>   copy(array2[4..8], array1[9..$]);
>>
>> where array1 had 10 elements fails because it copies data off 
>> the
>> end of array1, and if I use straight assignment the slices must
>> be the same length.
>>
>> Craig
>
>
> warning: untested!
>
> void myCopy(T)(T[] a, T[] b)
> {
>     auto possible = min(a.length, b.length);
>     a[0 .. possible] = b[0 .. possible];
> }
>
> myCopy(array2[4..8], array1[9..$]);
>
> Arrays only atm, but you could quite easily spruce that up in 
> to something much more generic.

Thanks. I ended up using something along these lines in my code
(although I didn't write a nice generic function as you have
done).





More information about the Digitalmars-d-learn mailing list