Make std.algorithm.copy examples clearer

Use meaningful variable names.
Add `take` example.
This commit is contained in:
Nick Treleaven 2014-10-24 17:22:00 +01:00
parent 15a4792d40
commit 80e092cd5a

View file

@ -8698,48 +8698,59 @@ if (isInputRange!Range1 && isOutputRange!(Range2, ElementType!Range1))
{ {
int[] a = [ 1, 5 ]; int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ]; int[] b = [ 9, 8 ];
int[] c = new int[a.length + b.length + 10]; int[] buf = new int[a.length + b.length + 10];
auto d = copy(b, copy(a, c)); auto rem = copy(a, buf); // copy a into buf
assert(c[0 .. a.length + b.length] == a ~ b); rem = copy(b, rem); // copy b into remainder of buf
assert(d.length == 10); assert(buf[0 .. a.length + b.length] == [1, 5, 9, 8]);
assert(rem.length == 10); // unused slots in buf
} }
/** /**
As long as the target range elements support assignment from source As long as the target range elements support assignment from source
range elements, different types of ranges are accepted. range elements, different types of ranges are accepted:
*/ */
@safe unittest @safe unittest
{ {
float[] a = [ 1.0f, 5 ]; float[] src = [ 1.0f, 5 ];
double[] b = new double[a.length]; double[] dest = new double[src.length];
auto d = copy(a, b); copy(src, dest);
} }
/** /**
To copy at most $(D n) elements from range $(D a) to range $(D b), you To _copy at most $(D n) elements from a range, you may want to use
may want to use $(D copy(take(a, n), b)). To copy those elements from $(XREF range, take):
range $(D a) that satisfy predicate $(D pred) to range $(D b), you may
want to use $(D copy(a.filter!(pred), b)).
*/ */
@safe unittest @safe unittest
{ {
int[] a = [ 1, 5, 8, 9, 10, 1, 2, 0 ]; int[] src = [ 1, 5, 8, 9, 10 ];
auto b = new int[a.length]; auto dest = new int[3];
auto c = copy(a.filter!(a => (a & 1) == 1), b); copy(take(src, dest.length), dest);
assert(b[0 .. $ - c.length] == [ 1, 5, 9, 1 ]); assert(dest[0 .. $] == [ 1, 5, 8 ]);
}
/**
To _copy just those elements from a range that satisfy a predicate you
may want to use $(LREF filter):
*/
@safe unittest
{
int[] src = [ 1, 5, 8, 9, 10, 1, 2, 0 ];
auto dest = new int[src.length];
auto rem = copy(src.filter!(a => (a & 1) == 1), dest);
assert(dest[0 .. $ - rem.length] == [ 1, 5, 9, 1 ]);
} }
/** /**
$(XREF range, retro) can be used to achieve behavior similar to $(XREF range, retro) can be used to achieve behavior similar to
$(WEB sgi.com/tech/stl/copy_backward.html, STL's copy_backward'). $(WEB sgi.com/tech/stl/copy_backward.html, STL's copy_backward'):
*/ */
@safe unittest @safe unittest
{ {
import std.algorithm, std.range; import std.algorithm, std.range;
int[] src = [1, 2, 4]; int[] src = [1, 2, 4];
int[] dst = [0, 0, 0, 0, 0]; int[] dest = [0, 0, 0, 0, 0];
copy(src.retro, dst.retro); copy(src.retro, dest.retro);
assert(dst == [0, 0, 1, 2, 4]); assert(dest == [0, 0, 1, 2, 4]);
} }
@safe unittest @safe unittest