Dense multidimensional std.container.array?
ZombineDev via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jan 26 10:07:40 PST 2016
On Tuesday, 26 January 2016 at 14:55:53 UTC, Wilson wrote:
> Just wondering how to create a dense multidimensional array
> with the GC free array container? I don't want to use an array
> of arrays but I do want the array[0][0] notation.
I suggest using std.experimental.ndslice [1] for multidimensional
arrays and std.experimental.allocator [2] for GC-free allocation.
For an introduction to the design ideas behind [2], you can also
check Andrei's talk at DConf [3].
Here's an example:
import std.stdio : writeln;
import std.experimental.allocator : makeArray, dispose;
import std.experimental.allocator.mallocator : Mallocator;
import std.experimental.ndslice : sliced;
void main()
{
ulong[] arr = Mallocator.instance.makeArray!ulong(36);
scope (exit) Mallocator.instance.dispose(arr);
// All of the below matrices refer to the same array
// that was allocated above.
auto matrix4x9 = arr.sliced(4, 9); // 2D 4x9 matrix
auto matrix6x6 = arr.sliced(6, 6); // 2D 6x6 matrix
auto matrix2x3x6 = arr.sliced(2, 3, 6); // 3D 2x3x6 matrix
// matrix.length!N - gets the number of elements in the Nth
dimention
foreach (rowIdx; 0 .. matrix6x6.length!0)
foreach (columnIdx; 0 .. matrix6x6.length!1)
matrix6x6[rowIdx, columnIdx] = (rowIdx + 1) * 10 + columnIdx
+ 1;
writeln (matrix6x6);
writeln (matrix4x9);
writeln (matrix2x3x6);
// The memory allocated by arr will be freed implicitly here.
}
Which prints:
[[11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26], [31, 32, 33,
34, 35, 36], [41, 42, 43, 44, 45, 46], [51, 52, 53, 54, 55, 56],
[61, 62, 63, 64, 65, 66]]
[[11, 12, 13, 14, 15, 16, 21, 22, 23], [24, 25, 26, 31, 32, 33,
34, 35, 36], [41, 42, 43, 44, 45, 46, 51, 52, 53], [54, 55, 56,
61, 62, 63, 64, 65, 66]]
[[[11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26], [31, 32,
33, 34, 35, 36]], [[41, 42, 43, 44, 45, 46], [51, 52, 53, 54, 55,
56], [61, 62, 63, 64, 65, 66]]]
[1]: http://dlang.org/phobos-prerelease/std_experimental_ndslice
[2]: http://dlang.org/phobos-prerelease/std_experimental_allocator
[3]: http://dconf.org/2015/talks/alexandrescu.html
More information about the Digitalmars-d-learn
mailing list