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 Name | Description |
|---|---|
array | Returns a copy of the input in a newly allocated dynamic array. |
appender | Returns a new Appender or RefAppender initialized with a given array. |
assocArray | Returns a newly allocated associative array from a range of key/value tuples. |
byPair | Construct a range iterating over an associative array by key/value tuples. |
insertInPlace | Inserts into an existing array at a given position. |
join | Concatenates a range of ranges into one array. |
minimallyInitializedArray | Returns a new array of type T. |
replace | Returns a new array with all occurrences of a certain subrange replaced. |
replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. |
replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. |
replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. |
replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. |
replaceSlice | Returns a new array with a given slice replaced. |
replicate | Creates a new array out of several copies of an input array or range. |
sameHead | Checks if the initial segments of two arrays refer to the same place in memory. |
sameTail | Checks if the final segments of two arrays refer to the same place in memory. |
split | Eagerly split a range or string into an array. |
staticArray | Creates a new static array from given data. |
uninitializedArray | Returns a new array of type T without initializing its elements. |
Allocates an array and initializes it with copies of the elements of range r.
Narrow strings are handled as a special case in an overload.
Range r
| range (or aggregate with opApply function) whose elements are copied into the allocated array |
auto a = array([1, 2, 3, 4, 5][]); writeln(a); // [1, 2, 3, 4, 5]
Convert a narrow string to an array type that fully supports random access. This is handled as a special case and always returns an array of dchar
String str
|
isNarrowString to be converted to an array of dchar
|
dchar[], const(dchar)[], or immutable(dchar)[] depending on the constness of the input.import std.range.primitives : isRandomAccessRange;
writeln("Hello D".array); // "Hello D"d
static assert(isRandomAccessRange!string == false);
writeln("Hello D"w.array); // "Hello D"d
static assert(isRandomAccessRange!dstring == true);
Returns a newly allocated associative array from a range of key/value tuples or from a range of keys and a range of values.
Range r
| An input range of tuples of keys and values. |
Keys keys
| An input range of keys |
Values values
| An input range of values |
std.typecons.Tuple, std.range.zip
import std.range : repeat, zip;
import std.typecons : tuple;
auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap
static assert(is(typeof(a) == string[int]));
writeln(a); // [0:"a", 1:"b", 2:"c"]
auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
static assert(is(typeof(b) == string[string]));
writeln(b); // ["foo":"bar", "baz":"quux"]
auto c = assocArray("ABCD", true.repeat);
static assert(is(typeof(c) == bool[dchar]));
bool[dchar] expected = ['D':true, 'A':true, 'B':true, 'C':true];
writeln(c); // expected
Construct a range iterating over an associative array by key/value tuples.
AA aa
| The associative array to iterate over. |
.key and .value). or by integer index (0 and 1 respectively).import std.algorithm.sorting : sort;
import std.typecons : tuple, Tuple;
auto aa = ["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)
]);
Returns a new array of type T allocated on the garbage collected heap without initializing its elements. This can be a useful optimization if every element will be immediately initialized. T may be a multidimensional array. In this case sizes may be specified for any number of dimensions from 0 to the number in T.
uninitializedArray is nothrow and weakly pure.
uninitializedArray is @system if the uninitialized element type has pointers.
| T | The type of the resulting array elements |
I sizes
| The length dimension(s) of the resulting array |
T with I.length dimensions.double[] arr = uninitializedArray!(double[])(100); writeln(arr.length); // 100 double[][] matrix = uninitializedArray!(double[][])(42, 31); writeln(matrix.length); // 42 writeln(matrix[0].length); // 31 char*[] ptrs = uninitializedArray!(char*[])(100); writeln(ptrs.length); // 100
Returns a new array of type T allocated on the garbage collected heap.
Partial initialization is done for types with indirections, for preservation of memory safety. Note that elements will only be initialized to 0, but not necessarily the element type's .init.
minimallyInitializedArray is nothrow and weakly pure.
| T | The type of the array elements |
I sizes
| The length dimension(s) of the resulting array |
T with I.length dimensions.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 = new int[42]; assert(arr2.equal(0.repeat(42)));
Returns the overlapping portion, if any, of two arrays. Unlike equal, overlap only compares the pointers and lengths in the ranges, not the values referred by them. If r1 and r2 have an overlapping slice, returns that slice. Otherwise, returns the null slice.
T[] a
| The first array to compare |
U[] b
| The second array to compare |
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 same
assert(overlap(a, b).empty);
static test()() @nogc
{
auto a = "It's three o'clock"d;
auto b = a[5 .. 10];
return b.overlap(a);
}
//works at compile-time
static assert(test == "three"d);
Inserts stuff (which must be an input range or any number of implicitly convertible items) in array at position pos.
T[] array
| The array that stuff will be inserted into. |
size_t pos
| The position in array to insert the stuff. |
U stuff
| An input range, or any number of implicitly convertible items to insert into array. |
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]
Returns whether the fronts of lhs and rhs both refer to the same place in memory, making one of the arrays a slice of the other which starts at index 0.
T[] lhs
| the first array to compare |
T[] rhs
| the second array to compare |
true if lhs.ptr == rhs.ptr, false otherwise.auto a = [1, 2, 3, 4, 5]; auto b = a[0 .. 2]; assert(a.sameHead(b));
Returns whether the backs of lhs and rhs both refer to the same place in memory, making one of the arrays a slice of the other which end at index $.
T[] lhs
| the first array to compare |
T[] rhs
| the second array to compare |
true if both arrays are the same length and lhs.ptr == rhs.ptr, false otherwise.auto a = [1, 2, 3, 4, 5]; auto b = a[3..$]; assert(a.sameTail(b));
S s
| an input range or a dynamic array |
size_t n
| number of times to repeat s
|
s repeated n times. This function allocates, fills, and returns a new array. std.range.repeat.auto a = "abc"; auto s = 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); // []
Eagerly splits range into an array, using sep 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).
The range must be a forward range. The separator can be a value of the same type as the elements in range or it can be another forward range.
S s
| the string to split by word if no separator is given |
Range range
| the range to split |
Separator sep
| a value of the same type as the elements of range or another |
| isTerminator | a predicate that splits the range when it returns true. |
range (or the words of s). std.algorithm.iteration.splitter for a lazy version without allocating memory. std.regex.splitter for a version that splits using a regular expression defined separator.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"]
string str = "Hello World!"; writeln(str.split); // ["Hello", "World!"] string str2 = "Hello\t\tWorld\t!"; writeln(str2.split); // ["Hello", "World", "!"]
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]]
Eagerly concatenates all of the ranges in ror together (with the GC) into one array using sep as the separator if present.
RoR ror
| An input range of input ranges |
R sep
| An input range, or a single element, to join the ranges on |
std.algorithm.iteration.joiner
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"
Replace occurrences of from with to in subject in a new array.
E[] subject
| the array to scan |
R1 from
| the item to replace |
R2 to
| the item to replace all instances of from with |
subject, or the original array if no match is found. std.algorithm.iteration.substitute for a lazy replace.writeln("Hello Wörld".replace("o Wö", "o Wo")); // "Hello World"
writeln("Hello Wörld".replace("l", "h")); // "Hehho Wörhd"
Replace occurrences of from with to in subject and output the result into sink.
Sink sink
| an output range |
E[] subject
| the array to scan |
R1 from
| the item to replace |
R2 to
| the item to replace all instances of from with |
std.algorithm.iteration.substitute for a lazy replace.auto arr = [1, 2, 3, 4, 5]; auto from = [2, 3]; auto to = [4, 6]; auto sink = appender!(int[])(); replaceInto(sink, arr, from, to); writeln(sink.data); // [1, 4, 6, 4, 5]
Replaces elements from array with indices ranging from from (inclusive) to to (exclusive) with the range stuff.
T[] subject
| the array to scan |
size_t from
| the starting index |
size_t to
| the ending index |
Range stuff
| the items to replace in-between from and to
|
subject. std.algorithm.iteration.substitute for a lazy replace.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]
Replaces elements from array with indices ranging from from (inclusive) to to (exclusive) with the range stuff. Expands or shrinks the array as needed.
T[] array
| the array to scan |
size_t from
| the starting index |
size_t to
| the ending index |
Range stuff
| the items to replace in-between from and to
|
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]
Replaces the first occurrence of from with to in subject.
E[] subject
| the array to scan |
R1 from
| the item to replace |
R2 to
| the item to replace from with |
subject, or the original array if no match is found.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"
Replaces the last occurrence of from with to in subject.
E[] subject
| the array to scan |
R1 from
| the item to replace |
R2 to
| the item to replace from with |
subject, or the original array if no match is found.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"
Creates a new array such that the items in slice are replaced with the items in replacement. slice and replacement do not need to be the same length. The result will grow or shrink based on the items given.
inout(T)[] s
| the base of the new array |
T[] slice
| the slice of s to be replaced |
T[] replacement
| the items to replace slice with |
s with slice replaced by replacement[]. std.algorithm.iteration.substitute for a lazy replace.auto a = [1, 2, 3, 4, 5]; auto b = replaceSlice(a, a[1 .. 4], [0, 0, 0]); writeln(b); // [1, 0, 0, 0, 5]
Implements an output range that appends data to an array. This is recommended over array ~= data when appending many elements because it is more efficient. Appender maintains its own array metadata locally, so it can avoid global locking for each append where capacity is non-zero.
| A | the array type to simulate. |
appenderauto 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);
app2.put([ 4, 5, 6 ]);
writeln(app2[]); // [1, 2, 3, 4, 5, 6]
Constructs an Appender with a given array. Note that this does not copy the data. If the array has a larger capacity as determined by arr.capacity, it will be used by the appender. After initializing an appender on an array, appending to the original array will reallocate.
Reserve at least newCapacity elements for appending. Note that more elements may be reserved than requested. If newCapacity <= capacity, then nothing is done.
size_t newCapacity
| the capacity the Appender should have |
0 will be returned.Use opSlice() from now on.
Appends item to the managed array. Performs encoding for char types if A is a differently typed char array.
U item
| the single item to append |
Appends an entire range to the managed array. Performs encoding for char elements if A is a differently typed char array.
Range items
| the range of items to append |
Appends to the managed array.
Appender.putClears the managed array. This allows the elements of the array to be reused for appending.
Appender might overwrite immutable data.Shrinks the managed array to the given length.
Exception if newlength is greater than the current array length. Gives a string in the form of Appender!(A)(data).
Writer w
| A char accepting output range. |
FormatSpec!char fmt
| A std.format.FormatSpec which controls how the array is formatted. |
string if writer is not set; void otherwise.A version of Appender 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.
arrayPtr overload of appender for construction with type-inference. | A | The array type to simulate |
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);
Constructs a RefAppender with a given array reference. This does not copy the data. If the array has a larger capacity as determined by arr.capacity, it will be used by the appender.
~=) 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. A* arr
| Pointer to an array. Must not be null. |
Wraps remaining Appender methods such as put.
| fn | Method name to call. |
Args args
| Arguments to pass to the method. |
Appends rhs to the managed array.
U rhs
| Element or range. |
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 returns 0.
Convenience function that returns an Appender instance, optionally initialized with array.
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 elements
w.put("bc"); // multiple elements
// use the append syntax
w ~= 'd';
w ~= "ef";
writeln(w[]); // "abcdef"
Convenience function that returns a RefAppender instance initialized with arrayPtr. Don't use null for the array pointer, use the other version of appender instead.
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);
Constructs a static array from a. The type of elements can be specified implicitly so that [1, 2].staticArray results in int[2], or explicitly, e.g. [1, 2].staticArray!float returns float[2]. When a is a range whose length is not known at compile time, the number of elements must be given as template argument (e.g. myrange.staticArray!2). Size and type can be combined, if the source range elements are implicitly convertible to the requested element type (eg: 2.iota.staticArray!(long[2])). When the range a is known at compile time, it can also be specified as a template argument to avoid having to specify the number of elements (e.g.: staticArray!(2.iota) or staticArray!(double, 2.iota)).
staticArray returns by value, so expressions involving large arrays may be inefficient. T[n] a
| The input elements. 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_t rangeLength
| outputs the number of elements used from a to it. Optional. |
a.auto a = [0, 1].staticArray; static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1]
import std.range : iota; auto input = 3.iota; auto a = input.staticArray!2; static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1] auto b = input.staticArray!(long[4]); static assert(is(typeof(b) == long[4])); writeln(b); // [0, 1, 2, 0]
import std.range : iota; enum a = staticArray!(2.iota); static assert(is(typeof(a) == int[2])); writeln(a); // [0, 1] enum b = staticArray!(long, 2.iota); static assert(is(typeof(b) == long[2])); writeln(b); // [0, 1]
© 1999–2019 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/std_array.html