Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.array

Functions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function NameDescription
arrayReturns a copy of the input in a newly allocated dynamic array.
appenderReturns a newAppender orRefAppender initialized with a given array.
assocArrayReturns a newly allocated associative array from a range of key/value tuples.
byPairConstruct a range iterating over an associative array by key/value tuples.
insertInPlaceInserts into an existing array at a given position.
joinConcatenates a range of ranges into one array.
minimallyInitializedArrayReturns a new array of typeT.
replaceReturns a new array with all occurrences of a certain subrange replaced.
replaceFirstReturns a new array with the first occurrence of a certain subrange replaced.
replaceInPlaceReplaces all occurrences of a certain subrange and puts the result into a given array.
replaceIntoReplaces all occurrences of a certain subrange and puts the result into an output range.
replaceLastReturns a new array with the last occurrence of a certain subrange replaced.
replaceSliceReturns a new array with a given slice replaced.
replicateCreates a new array out of several copies of an input array or range.
sameHeadChecks if the initial segments of two arrays refer to the same place in memory.
sameTailChecks if the final segments of two arrays refer to the same place in memory.
splitEagerly split a range or string into an array.
staticArrayCreates a new static array from given data.
uninitializedArrayReturns a new array of typeT without initializing its elements.
License:
Boost License 1.0.
Authors:
Andrei Alexandrescu andJonathan M Davis

Sourcestd/array.d

ForeachType!Range[]array(Range)(Ranger)
if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range);

ForeachType!(typeof((*Range).init))[]array(Range)(Ranger)
if (is(Range == U*, U) && isIterable!U && !isAutodecodableString!Range && !isInfinite!Range);
Allocates an array and initializes it with copies of the elements of ranger.
Narrow strings are handled as follows:
  • If autodecoding is turned on (default), then they are handled as a separate overload.
  • If autodecoding is turned off, then this is equivalent to duplicating the array.
Parameters:
Rangerrange (or aggregate withopApply function) whose elements are copied into the allocated array
Returns:
allocated and initialized array
Examples:
auto a =array([1, 2, 3, 4, 5][]);writeln(a);// [1, 2, 3, 4, 5]
CopyTypeQualifiers!(ElementType!String, dchar)[]array(String)(scope Stringstr)
if (isAutodecodableString!String);
Convert a narrow autodecoding string to an array type that fully supportsrandom access. This is handled as a special case and always returns an arrayofdchar

NOTEThis function is never used when autodecoding is turned off.

Parameters:
StringstrisNarrowString to be converted to an array ofdchar
Returns:
adchar[],const(dchar)[], orimmutable(dchar)[] depending on the constness of the input.
Examples:
import std.range.primitives : isRandomAccessRange;import std.traits : isAutodecodableString;// note that if autodecoding is turned off, `array` will not transcode these.staticif (isAutodecodableString!string)    writeln("Hello D".array);// "Hello D"delse    writeln("Hello D".array);// "Hello D"staticif (isAutodecodableString!wstring)    writeln("Hello D"w.array);// "Hello D"delse    writeln("Hello D"w.array);// "Hello D"wstaticassert(isRandomAccessRange!dstring ==true);
autoassocArray(Range)(Ranger)
if (isInputRange!Range);

autoassocArray(Keys, Values)(Keyskeys, Valuesvalues)
if (isInputRange!Values && isInputRange!Keys);
Returns a newly allocated associative array from a range of key/value tuplesor from a range of keys and a range of values.
Parameters:
RangerAninput range of tuples of keys and values.
KeyskeysAninput range of keys
ValuesvaluesAninput range of values
Returns:
A newly allocated associative array out of elements of the input range, which must be a range of tuples (Key, Value) or a range of keys and a range of values. If given two ranges of unequal lengths after the elements of the shorter are exhausted the remaining elements of the longer will not be considered. Returns a null associative array reference when given an empty range.

DuplicatesAssociative arrays have unique keys. If r contains duplicate keys, then the result will contain the value of the last pair for that key in r.

See Also:
Examples:
import std.range : repeat, zip;import std.typecons : tuple;import std.range.primitives : autodecodeStrings;auto a =assocArray(zip([0, 1, 2], ["a","b","c"]));// aka zipMapstaticassert(is(typeof(a) == string[int]));writeln(a);// [0:"a", 1:"b", 2:"c"]auto b =assocArray([ tuple("foo","bar"), tuple("baz","quux") ]);staticassert(is(typeof(b) == string[string]));writeln(b);// ["foo":"bar", "baz":"quux"]staticif (autodecodeStrings)alias achar =dchar;elsealias achar =immutable(char);auto c =assocArray("ABCD",true.repeat);staticassert(is(typeof(c) ==bool[achar]));bool[achar] expected = ['D':true, 'A':true, 'B':true, 'C':true];writeln(c);// expected
autobyPair(AA)(AAaa)
if (isAssociativeArray!AA);
Construct a range iterating over an associative array by key/value tuples.
Parameters:
AAaaThe associative array to iterate over.
Returns:
Aforward rangeof Tuple's of key and value pairs from the given associative array. The membersof each pair can be accessed by name (.key and.value). or by integerindex (0 and 1 respectively).
Examples:
import std.algorithm.sorting : sort;import std.typecons : tuple, Tuple;autoaa = ["a": 1,"b": 2,"c": 3];Tuple!(string,int)[] pairs;// Iteration over key/value pairs.foreach (pair;aa.byPair){if (pair.key =="b")        pairs ~= tuple("B", pair.value);else        pairs ~= pair;}// Iteration order is implementation-dependent, so we should sort it to get// a fixed order.pairs.sort();assert(pairs == [    tuple("B", 2),    tuple("a", 1),    tuple("c", 3)]);
nothrow @system autouninitializedArray(T, I...)(Isizes)
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && hasIndirections!(ElementEncodingType!T));

nothrow @trusted autouninitializedArray(T, I...)(Isizes)
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && !hasIndirections!(ElementEncodingType!T));
Returns a new array of typeT allocated on the garbage collected heapwithout initializing its elements. This can be a useful optimization if everyelement will be immediately initialized.T may be a multidimensionalarray. In this case sizes may be specified for any number of dimensions from 0to the number inT.
uninitializedArray isnothrow and weaklypure.
uninitializedArray is@system if the uninitialized element type has pointers.
Parameters:
TThe type of the resulting array elements
IsizesThe length dimension(s) of the resulting array
Returns:
An array ofT withI.length dimensions.
Examples:
double[] arr =uninitializedArray!(double[])(100);writeln(arr.length);// 100double[][] matrix =uninitializedArray!(double[][])(42, 31);writeln(matrix.length);// 42writeln(matrix[0].length);// 31char*[] ptrs =uninitializedArray!(char*[])(100);writeln(ptrs.length);// 100
nothrow @trusted autominimallyInitializedArray(T, I...)(Isizes)
if (isDynamicArray!T && allSatisfy!(isIntegral, I));
Returns a new array of typeT allocated on the garbage collected heap.
Partial initialization is done for types with indirections, for preservationof memory safety. Note that elements will only be initialized to 0, but notnecessarily the element type's.init.
minimallyInitializedArray isnothrow and weaklypure.
Parameters:
TThe type of the array elements
IsizesThe length dimension(s) of the resulting array
Returns:
An array ofT withI.length dimensions.
Examples:
import std.algorithm.comparison : equal;import std.range : repeat;auto arr =minimallyInitializedArray!(int[])(42);writeln(arr.length);// 42// Elements aren't necessarily initialized to 0, so don't do this:// assert(arr.equal(0.repeat(42)));// If that is needed, initialize the array normally instead:auto arr2 =newint[42];assert(arr2.equal(0.repeat(42)));
@trusted CommonType!(T[], U[])overlap(T, U)(T[]a, U[]b)
if (is(typeof(a.ptr <b.ptr) == bool));
Returns the overlapping portion, if any, of two arrays. Unlikeequal,overlap only compares the pointers and lengths in theranges, not the values referred by them. Ifr1 andr2 have anoverlapping slice, returns that slice. Otherwise, returns the nullslice.
Parameters:
T[]aThe first array to compare
U[]bThe second array to compare
Returns:
The overlapping portion of the two arrays.
Examples:
int[]a = [ 10, 11, 12, 13, 14 ];int[]b =a[1 .. 3];writeln(overlap(a,b));// [11, 12]b =b.dup;// overlap disappears even though the content is the sameassert(overlap(a,b).empty);static test()() @nogc{autoa ="It's three o'clock"d;autob =a[5 .. 10];returnb.overlap(a);}//works at compile-timestaticassert(test =="three"d);
Examples:
import std.meta : AliasSeq;// can be used as an alternative implementation of overlap that returns// `true` or `false` instead of a slice of the overlapbool isSliceOf(T)(constscope T[] part,constscope T[] whole){return part.overlap(whole)is part;}auto x = [1, 2, 3, 4, 5];assert(isSliceOf(x[3..$], x));assert(isSliceOf(x[], x));assert(!isSliceOf(x, x[3..$]));assert(!isSliceOf([7, 8], x));assert(isSliceOf(null, x));// null is a slice of itselfassert(isSliceOf(null,null));foreach (T; AliasSeq!(int[],const(int)[],immutable(int)[],constint[],immutableint[])){    Ta = [1, 2, 3, 4, 5];    Tb =a;    T c =a[1 .. $];    T d =a[0 .. 1];    T e =null;assert(isSliceOf(a,a));assert(isSliceOf(b,a));assert(isSliceOf(a,b));assert(isSliceOf(c,a));assert(isSliceOf(c,b));assert(!isSliceOf(a, c));assert(!isSliceOf(b, c));assert(isSliceOf(d,a));assert(isSliceOf(d,b));assert(!isSliceOf(a, d));assert(!isSliceOf(b, d));assert(isSliceOf(e,a));assert(isSliceOf(e,b));assert(isSliceOf(e, c));assert(isSliceOf(e, d));//verifies R-value compatibiltyassert(!isSliceOf(a[$ .. $],a));assert(isSliceOf(a[0 .. 0],a));assert(isSliceOf(a,a[0.. $]));assert(isSliceOf(a[0 .. $],a));}
voidinsertInPlace(T, U...)(ref T[]array, size_tpos, Ustuff)
if (!isSomeString!(T[]) && allSatisfy!(isInputRangeOrConvertible!T, U) && (U.length > 0));

voidinsertInPlace(T, U...)(ref T[]array, size_tpos, Ustuff)
if (isSomeString!(T[]) && allSatisfy!(isCharOrStringOrDcharRange, U));
Insertsstuff (which must be an input range or any number of implicitly convertible items) inarray at positionpos.
Parameters:
T[]arrayThe array thatstuff will be inserted into.
size_tposThe position inarray to insert thestuff.
UstuffAninput range, or any number of implicitly convertible items to insert intoarray.
Examples:
int[] a = [ 1, 2, 3, 4 ];a.insertInPlace(2, [ 1, 2 ]);writeln(a);// [1, 2, 1, 2, 3, 4]a.insertInPlace(3, 10u, 11);writeln(a);// [1, 2, 1, 10, 11, 2, 3, 4]union U{float a = 3.0;int b;}U u1 = { b : 3 };U u2 = { b : 4 };U u3 = { b : 5 };U[] unionArr = [u2, u3];unionArr.insertInPlace(2, [u1]);writeln(unionArr);// [u2, u3, u1]unionArr.insertInPlace(0, [u3, u2]);writeln(unionArr);// [u3, u2, u2, u3, u1]staticclass C{int a;float b;this(int a,float b) {this.a = a;this.b = b; }}C c1 =new C(42, 1.0);C c2 =new C(0, 0.0);C c3 =new C(int.max,float.init);C[] classArr = [c1, c2, c3];insertInPlace(classArr, 3, [c2, c3]);C[5] classArr1 = classArr;writeln(classArr1);// [c1, c2, c3, c2, c3]insertInPlace(classArr, 0, c3, c1);C[7] classArr2 = classArr;writeln(classArr2);// [c3, c1, c1, c2, c3, c2, c3]
pure nothrow @nogc @safe boolsameHead(T)(in T[]lhs, in T[]rhs);
Returns whether thefronts oflhs andrhs both refer to the same place in memory, making one of the arrays a slice of the other which starts at index0.
Parameters:
T[]lhsthe first array to compare
T[]rhsthe second array to compare
Returns:
true iflhs.ptr == rhs.ptr,false otherwise.
Examples:
auto a = [1, 2, 3, 4, 5];auto b = a[0 .. 2];assert(a.sameHead(b));
pure nothrow @nogc @trusted boolsameTail(T)(in T[]lhs, in T[]rhs);
Returns whether thebacks oflhs andrhs both refer to the same place in memory, making one of the arrays a slice of the other which end at index$.
Parameters:
T[]lhsthe first array to compare
T[]rhsthe second array to compare
Returns:
true if both arrays are the same length andlhs.ptr == rhs.ptr,false otherwise.
Examples:
auto a = [1, 2, 3, 4, 5];auto b = a[3..$];assert(a.sameTail(b));
ElementEncodingType!S[]replicate(S)(Ss, size_tn)
if (isDynamicArray!S);

ElementType!S[]replicate(S)(Ss, size_tn)
if (isInputRange!S && !isDynamicArray!S);
Parameters:
Ssaninput range or a dynamic array
size_tnnumber of times to repeats
Returns:
An array that consists ofs repeatedn times. This function allocates, fills, and returns a new array.
See Also:
For a lazy version, refer tostd.range.repeat.
Examples:
auto a ="abc";autos =replicate(a, 3);writeln(s);// "abcabcabc"auto b = [1, 2, 3];auto c =replicate(b, 3);writeln(c);// [1, 2, 3, 1, 2, 3, 1, 2, 3]auto d =replicate(b, 0);writeln(d);// []
pure @safe S[]split(S)(Ss)
if (isSomeString!S);

autosplit(Range, Separator)(Rangerange, Separatorsep)
if (isForwardRange!Range && (is(typeof(ElementType!Range.init == Separator.init)) || is(typeof(ElementType!Range.init == ElementType!Separator.init)) && isForwardRange!Separator));

autosplit(alias isTerminator, Range)(Rangerange)
if (isForwardRange!Range && is(typeof(unaryFun!isTerminator(range.front))));
Eagerly splitsrange into an array, usingsep as the delimiter.
When no delimiter is provided, strings are split into an array of words,using whitespace as delimiter.Runs of whitespace are merged together (no empty words are produced).
Therange must be aforward range.The separator can be a value of the same type as the elements inrangeor it can be another forwardrange.
Parameters:
Ssthe string to split by word if no separator is given
Rangerangethe range to split
Separatorsepa value of the same type as the elements ofrange or another
isTerminatora predicate that splits the range when it returnstrue.
Returns:
An array containing the divided parts ofrange (or the words ofs).
See Also:
std.algorithm.iteration.splitter for a lazy version without allocating memory.
std.regex.splitter for a version that splits using a regularexpression defined separator.
Examples:
import std.uni : isWhite;writeln("Learning,D,is,fun".split(","));// ["Learning", "D", "is", "fun"]writeln("Learning D is fun".split!isWhite);// ["Learning", "D", "is", "fun"]writeln("Learning D is fun".split(" D "));// ["Learning", "is fun"]
Examples:
string str ="Hello World!";writeln(str.split);// ["Hello", "World!"]string str2 ="Hello\t\tWorld\t!";writeln(str2.split);// ["Hello", "World", "!"]
Examples:
writeln(split("hello world"));// ["hello", "world"]writeln(split("192.168.0.1","."));// ["192", "168", "0", "1"]auto a =split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]);writeln(a);// [[1], [4, 5, 1], [4, 5]]
ElementEncodingType!(ElementType!RoR)[]join(RoR, R)(RoRror, Rsep)
if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)));

ElementEncodingType!(ElementType!RoR)[]join(RoR, E)(RoRror, scope Esep)
if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && (is(E : ElementType!(ElementType!RoR)) || !autodecodeStrings && isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!E));

ElementEncodingType!(ElementType!RoR)[]join(RoR)(RoRror)
if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)));
Eagerly concatenates all of the ranges inror together (with the GC) into one array usingsep as the separator if present.
Parameters:
RoRrorAninput range of input ranges
RsepAn input range, or a single element, to join the ranges on
Returns:
An array of elements
See Also:
For a lazy version, seestd.algorithm.iteration.joiner
Examples:
writeln(join(["hello","silly","world"]," "));// "hello silly world"writeln(join(["hello","silly","world"]));// "hellosillyworld"writeln(join([[1, 2, 3], [4, 5]], [72, 73]));// [1, 2, 3, 72, 73, 4, 5]writeln(join([[1, 2, 3], [4, 5]]));// [1, 2, 3, 4, 5]const string[] arr = ["apple","banana"];writeln(arr.join(","));// "apple,banana"writeln(arr.join());// "applebanana"
E[]replace(E, R1, R2)(E[]subject, R1from, R2to)
if (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1));
Replace occurrences offrom withto insubject in a new array.
Parameters:
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replace all instances offrom with
Returns:
A new array without changing the contents ofsubject, or the original array if no match is found.
See Also:
Examples:
writeln("Hello Wörld".replace("o Wö","o Wo"));// "Hello World"writeln("Hello Wörld".replace("l","h"));// "Hehho Wörhd"
E[]replace(E, R1, R2)(E[]subject, R1from, R2to, ref size_tchanged)
if (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1));
Replace occurrences offrom withto insubject in a new array.changed counts how many replacements took place.
Parameters:
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replace all instances offrom with
size_tchangedthe number of replacements
Returns:
A new array without changing the contents ofsubject, or the original array if no match is found.
Examples:
size_tchanged = 0;writeln("Hello Wörld".replace("o Wö","o Wo",changed));// "Hello World"writeln(changed);// 1changed = 0;writeln("Hello Wörld".replace("l","h",changed));// "Hehho Wörhd"import std.stdio : writeln;writeln(changed);writeln(changed);// 3
voidreplaceInto(E, Sink, R1, R2)(Sinksink, E[]subject, R1from, R2to)
if (isOutputRange!(Sink, E) && (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1)));
Replace occurrences offrom withto insubject and output the result intosink.
Parameters:
Sinksinkanoutput range
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replace all instances offrom with
See Also:
Examples:
auto arr = [1, 2, 3, 4, 5];autofrom = [2, 3];autoto = [4, 6];autosink = appender!(int[])();replaceInto(sink, arr,from,to);writeln(sink.data);// [1, 4, 6, 4, 5]
voidreplaceInto(E, Sink, R1, R2)(Sinksink, E[]subject, R1from, R2to, ref size_tchanged)
if (isOutputRange!(Sink, E) && (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1)));
Replace occurrences offrom withto insubject and output the result intosink.changed counts how many replacements took place.
Parameters:
Sinksinkanoutput range
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replace all instances offrom with
size_tchangedthe number of replacements
Examples:
auto arr = [1, 2, 3, 4, 5];autofrom = [2, 3];autoto = [4, 6];autosink = appender!(int[])();size_tchanged = 0;replaceInto(sink, arr,from,to,changed);writeln(sink.data);// [1, 4, 6, 4, 5]writeln(changed);// 1
T[]replace(T, Range)(T[]subject, size_tfrom, size_tto, Rangestuff)
if (isInputRange!Range && (is(ElementType!Range : T) || isSomeString!(T[]) && is(ElementType!Range : dchar)));
Replaces elements fromarray with indices ranging fromfrom (inclusive) toto (exclusive) with the rangestuff.
Parameters:
T[]subjectthe array to scan
size_tfromthe starting index
size_ttothe ending index
Rangestuffthe items to replace in-betweenfrom andto
Returns:
A new array without changing the contents ofsubject.
See Also:
Examples:
auto a = [ 1, 2, 3, 4 ];auto b = a.replace(1, 3, [ 9, 9, 9 ]);writeln(a);// [1, 2, 3, 4]writeln(b);// [1, 9, 9, 9, 4]
voidreplaceInPlace(T, Range)(ref T[]array, size_tfrom, size_tto, Rangestuff)
if (is(typeof(replace(array,from,to,stuff))));
Replaces elements fromarray with indices ranging fromfrom (inclusive) toto (exclusive) with the rangestuff. Expands or shrinks the array as needed.
Parameters:
T[]arraythe array to scan
size_tfromthe starting index
size_ttothe ending index
Rangestuffthe items to replace in-betweenfrom andto
Examples:
int[] a = [1, 4, 5];replaceInPlace(a, 1u, 2u, [2, 3, 4]);writeln(a);// [1, 2, 3, 4, 5]replaceInPlace(a, 1u, 2u,cast(int[])[]);writeln(a);// [1, 3, 4, 5]replaceInPlace(a, 1u, 3u, a[2 .. 4]);writeln(a);// [1, 4, 5, 5]
E[]replaceFirst(E, R1, R2)(E[]subject, R1from, R2to)
if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1]))));
Replaces the first occurrence offrom withto insubject.
Parameters:
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replacefrom with
Returns:
A new array without changing the contents ofsubject, or the original array if no match is found.
Examples:
auto a = [1, 2, 2, 3, 4, 5];auto b = a.replaceFirst([2], [1337]);writeln(b);// [1, 1337, 2, 3, 4, 5]auto s ="This is a foo foo list";auto r = s.replaceFirst("foo","silly");writeln(r);// "This is a silly foo list"
E[]replaceLast(E, R1, R2)(E[]subject, R1from, R2to)
if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1]))));
Replaces the last occurrence offrom withto insubject.
Parameters:
E[]subjectthe array to scan
R1fromthe item to replace
R2tothe item to replacefrom with
Returns:
A new array without changing the contents ofsubject, or the original array if no match is found.
Examples:
auto a = [1, 2, 2, 3, 4, 5];auto b = a.replaceLast([2], [1337]);writeln(b);// [1, 2, 1337, 3, 4, 5]auto s ="This is a foo foo list";auto r = s.replaceLast("foo","silly");writeln(r);// "This is a foo silly list"
inout(T)[]replaceSlice(T)(inout(T)[]s, in T[]slice, in T[]replacement);
Creates a new array such that the items inslice are replaced with the items inreplacement.slice andreplacement do not need to be the same length. The result will grow or shrink based on the items given.
Parameters:
inout(T)[]sthe base of the new array
T[]slicethe slice ofs to be replaced
T[]replacementthe items to replaceslice with
Returns:
A new array that iss withslice replaced byreplacement[].
See Also:
Examples:
auto a = [1, 2, 3, 4, 5];auto b =replaceSlice(a, a[1 .. 4], [0, 0, 0]);writeln(b);// [1, 0, 0, 0, 5]
structAppender(A) if (isDynamicArray!A);
Implements an output range that appends data to an array. This isrecommended overarray ~= data when appending many elements because it is moreefficient.Appender maintains its own array metadata locally, so it can avoidtheperformance hit of looking up slicecapacityfor each append.
Parameters:
Athe array type to simulate.
See Also:
Examples:
auto app = appender!string();string b ="abcdefg";foreach (char c; b)    app.put(c);writeln(app[]);// "abcdefg"int[] a = [ 1, 2 ];auto app2 = appender(a);app2.put(3);writeln(app2.length);// 3app2.put([ 4, 5, 6 ]);writeln(app2[]);// [1, 2, 3, 4, 5, 6]
@trusted this(Aarr);
Constructs anAppender with a given array. Note that this does not copy the data. If the array has a larger capacity as determined byarr.capacity, it will be used by the appender. After initializing an appender on an array, appending to the original array will reallocate.
voidreserve(size_tnewCapacity);
Reserve at least newCapacity elements for appending. Note that more elements may be reserved than requested. IfnewCapacity <= capacity, then nothing is done.
Parameters:
size_tnewCapacitythe capacity theAppender should have
@property size_tcapacity() const;
Returns:
the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate,0 will be returned.
@property size_tlength() const;
Returns:
The number of elements appended.
@property inout(T)[]data() inout;
Use opSlice() from now on.
Returns:
The managed array.
@property @trusted inout(T)[]opSlice() inout;
Returns:
The managed array.
voidput(U)(Uitem)
if (canPutItem!U);
Appendsitem to the managed array. Performs encoding forchar types ifA is a differently typedchar array.
Parameters:
Uitemthe single item to append
voidput(Range)(Rangeitems)
if (canPutRange!Range);
Appends an entire range to the managed array. Performs encoding forchar elements ifA is a differently typedchar array.
Parameters:
Rangeitemsthe range of items to append
templateopOpAssign(string op : "~")
Appends to the managed array.
See Also:
pure nothrow @trusted voidclear();
Clears the managed array. This allows the elements of the array to be reused for appending.

Noteclear is disabled for immutable or const element types, due to the possibility thatAppender might overwrite immutable data.

pure @trusted voidshrinkTo(size_tnewlength);
Shrinks the managed array to the given length.
Throws:
Exception if newlength is greater than the current array length.

NoteshrinkTo is disabled for immutable or const element types.

stringtoString()() const;

voidtoString(Writer)(ref Writerw, ref scope const FormatSpec!charfmt) const
if (isOutputRange!(Writer, char));
Gives a string in the form ofAppender!(A)(data).
Parameters:
WriterwAchar acceptingoutput range.
FormatSpec!charfmtAstd.format.FormatSpec which controls how the array is formatted.
Returns:
Astring ifwriter is not set;void otherwise.
structRefAppender(A) if (isDynamicArray!A);
A version ofAppender that can update an array in-place. It forwards all calls to an underlying appender implementation. Any calls made to the appender also update the pointer to the original array passed in.

TipUse thearrayPtr overload ofappender for construction with type-inference.

Parameters:
AThe array type to simulate
Examples:
int[] a = [1, 2];auto app2 = appender(&a);writeln(app2[]);// [1, 2]writeln(a);// [1, 2]app2 ~= 3;writeln(app2.length);// 3app2 ~= [4, 5, 6];writeln(app2[]);// [1, 2, 3, 4, 5, 6]writeln(a);// [1, 2, 3, 4, 5, 6]app2.reserve(5);assert(app2.capacity >= 5);
this(A*arr);
Constructs aRefAppender with a given array reference. This does not copy the data. If the array has a larger capacity as determined byarr.capacity, it will be used by the appender.

NoteDo not use built-in appending (i.e.~=) on the original array until you are done with the appender, because subsequent calls to the appender will reallocate the array data without those appends.

Parameters:
A*arrPointer to an array. Must not be null.
voidopDispatch(string fn, Args...)(Argsargs)
if (__traits(compiles, (Appender!A a) => mixin("a." ~ fn ~ "(args)")));
Wraps remainingAppender methods such asput.
Parameters:
fnMethod name to call.
ArgsargsArguments to pass to the method.
voidopOpAssign(string op : "~", U)(Urhs)
if (__traits(compiles, (Appender!A a){a.put(rhs);}));
Appendsrhs to the managed array.
Parameters:
UrhsElement or range.
@property size_tcapacity() const;
Returns the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate,capacity returns0.
@property size_tlength() const;
Returns:
The number of elements appended.
@property inout(ElementEncodingType!A)[]opSlice() inout;
Returns:
the managed array.
Appender!Aappender(A)()
if (isDynamicArray!A);

Appender!(E[])appender(A : E[], E)(auto ref Aarray);
Convenience function that returns anAppender instance, optionally initialized witharray.
Examples:
auto w =appender!string;// pre-allocate space for at least 10 elements (this avoids costly reallocations)w.reserve(10);assert(w.capacity >= 10);w.put('a');// single elementsw.put("bc");// multiple elements// use the append syntaxw ~= 'd';w ~="ef";writeln(w[]);// "abcdef"
RefAppender!(E[])appender(P : E[]*, E)(ParrayPtr);
Convenience function that returns aRefAppender instance initialized witharrayPtr. Don't use null for the array pointer, use the other version ofappender instead.
Examples:
int[] a = [1, 2];auto app2 =appender(&a);writeln(app2[]);// [1, 2]writeln(a);// [1, 2]app2 ~= 3;app2 ~= [4, 5, 6];writeln(app2[]);// [1, 2, 3, 4, 5, 6]writeln(a);// [1, 2, 3, 4, 5, 6]app2.reserve(5);assert(app2.capacity >= 5);
T[n]staticArray(T, size_t n)(auto ref T[n]a);

U[n]staticArray(U, T, size_t n)(auto ref T[n]a)
if (!is(T == U) && is(T : U));
Constructs a static array from a dynamic array whose length is known at compile-time.The element type can be inferred or specified explicitly:
  • [1, 2].staticArray returnsint[2]
  • [1, 2].staticArray!float returnsfloat[2]

NotestaticArray returns by value, so expressions involving large arrays may be inefficient.

Parameters:
T[n]aThe input array.
Returns:
A static array constructed froma.
Examples:
static array from array literal
autoa = [0, 1].staticArray;staticassert(is(typeof(a) ==int[2]));writeln(a);// [0, 1]
Examples:
static array from array with implicit casting of elements
auto b = [0, 1].staticArray!long;staticassert(is(typeof(b) ==long[2]));writeln(b);// [0, 1]
autostaticArray(size_t n, T)(scope Ta)
if (isInputRange!T);

autostaticArray(size_t n, T)(scope Ta, out size_trangeLength)
if (isInputRange!T);

autostaticArray(Un : U[n], U, size_t n, T)(scope Ta)
if (isInputRange!T && is(ElementType!T : U));

autostaticArray(Un : U[n], U, size_t n, T)(scope Ta, out size_trangeLength)
if (isInputRange!T && is(ElementType!T : U));

autostaticArray(alias a)()
if (isInputRange!(typeof(a)));

autostaticArray(U, alias a)()
if (isInputRange!(typeof(a)));
Constructs a static array from a range.Whena.length is not known at compile time, the number of elements must begiven as a template argument (e.g.myrange.staticArray!2).Size and type can be combined, if the source range elements are implicitlyconvertible to the requested element type (eg:2.iota.staticArray!(long[2])).
When the rangea is known at compile time, it can be given as atemplate argument to avoid having to specify the number of elements(e.g.:staticArray!(2.iota) orstaticArray!(double, 2.iota)).
Parameters:
TaThe input range. If there are less elements than the specified length of the static array, the rest of it is default-initialized. If there are more than specified, the first elements up to the specified length are used.
size_trangeLengthOutput for the number of elements used froma. Optional.
Examples:
static array from range + size
import std.range : iota;auto input = 3.iota;autoa = input.staticArray!2;staticassert(is(typeof(a) ==int[2]));writeln(a);// [0, 1]auto b = input.staticArray!(long[4]);staticassert(is(typeof(b) ==long[4]));writeln(b);// [0, 1, 2, 0]
Examples:
static array from CT range
import std.range : iota;enuma =staticArray!(2.iota);staticassert(is(typeof(a) ==int[2]));writeln(a);// [0, 1]enum b =staticArray!(long, 2.iota);staticassert(is(typeof(b) ==long[2]));writeln(b);// [0, 1]
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Thu Feb 19 20:48:38 2026

[8]ページ先頭

©2009-2026 Movatter.jp