copy

Copies the content of source into target and returns the remaining (unfilled) part of target.

Preconditions: target shall have enough room to accommodate the entirety of source.

  1. TargetRange copy(SourceRange source, TargetRange target)
    TargetRange
    copy
    (
    SourceRange
    TargetRange
    )
    (
    SourceRange source
    ,
    TargetRange target
    )
    if (
    areCopyCompatibleArrays!(SourceRange, TargetRange)
    )
  2. TargetRange copy(SourceRange source, TargetRange target)

Parameters

source
Type: SourceRange
target
Type: TargetRange

an output range

Return Value

Type: TargetRange

The unfilled part of target

Examples

1 int[] a = [ 1, 5 ];
2 int[] b = [ 9, 8 ];
3 int[] buf = new int[](a.length + b.length + 10);
4 auto rem = a.copy(buf);    // copy a into buf
5 rem = b.copy(rem);         // copy b into remainder of buf
6 assert(buf[0 .. a.length + b.length] == [1, 5, 9, 8]);
7 assert(rem.length == 10);   // unused slots in buf

As long as the target range elements support assignment from source range elements, different types of ranges are accepted:

float[] src = [ 1.0f, 5 ];
double[] dest = new double[src.length];
src.copy(dest);

To copy at most n elements from a range, you may want to use std.range.take:

1 import std.range;
2 int[] src = [ 1, 5, 8, 9, 10 ];
3 auto dest = new int[](3);
4 src.take(dest.length).copy(dest);
5 assert(dest == [ 1, 5, 8 ]);

To copy just those elements from a range that satisfy a predicate, use filter:

1 import std.algorithm.iteration : filter;
2 int[] src = [ 1, 5, 8, 9, 10, 1, 2, 0 ];
3 auto dest = new int[src.length];
4 auto rem = src
5     .filter!(a => (a & 1) == 1)
6     .copy(dest);
7 assert(dest[0 .. $ - rem.length] == [ 1, 5, 9, 1 ]);

std.range.retro can be used to achieve behavior similar to STL's copy_backward':

1 import std.algorithm, std.range;
2 int[] src = [1, 2, 4];
3 int[] dest = [0, 0, 0, 0, 0];
4 src.retro.copy(dest.retro);
5 assert(dest == [0, 0, 1, 2, 4]);
Suggestion Box / Bug Report