Assigning map result, and in-place map

Denis Koroskin 2korden at gmail.com
Fri Sep 3 03:41:09 PDT 2010


On Fri, 03 Sep 2010 14:32:47 +0400, Bert van Leeuwen <bert at e.co.za> wrote:

> Pelle Wrote:
>
>> On 09/03/2010 11:42 AM, Bert van Leeuwen wrote:
>>
>> > 2) Related to above, I want to do something like map, but not return  
>> a new array, I want to modify elements in-place in the array. How do I  
>> do that? (without explicitly iterating with foreach etc.)
>>
>> I don't know if this is intended to be supported, but at least for now
>> this works:
>>
>>      int[] xs = [1,2,3,4,5,6,7];
>>      copy(map!`a*a`(xs), xs);
>>
>>      writeln(xs);
>>
>> [1, 4, 9, 16, 25, 36, 49]
>
>
> Interesting. For large arrays, that seems to take almost double the time  
> of creating a new one with array() (as in Nick's reply). So copy()  
> obviously doesn't do it in place (not surprising given its name), and  
> presumably makes a temporary array first from which to copy to a.
>

I don't think you are right.
This is how copy is defined in std.algorithm[1]:

Range2 copy(Range1, Range2)(Range1 source, Range2 target)
if (isInputRange!Range1 && isOutputRange!(Range2, ElementType!Range1))
{
     for (; !source.empty; source.popFront())
     {
         put(target, source.front);
     }
     return target;
}

[1]  
http://dsource.org/projects/phobos/browser/trunk/phobos/std/algorithm.d#L4054


More information about the Digitalmars-d mailing list