[D1,static array] fill static multidimensional array.
spir
denis.spir at gmail.com
Fri Oct 22 01:57:39 PDT 2010
On Fri, 22 Oct 2010 01:50:56 +0000 (UTC)
%u <e at ee.com> wrote:
> What is the fastest way to fill a static multidimensional array?
>
> Looping over all dimension's elements sounds inefficient, especially as a
> static array is essentially continuous memory.
> What is the best practice?
>
> int[2][2][2] arr = 0;
> arr[] = 3; //Error: cannot implicitly convert expression (3) of type int to
> int[2u][2u][]
> arr[][][] = 3; // this would be fine too :)
>
> int[2][2][2] arr2 = [[[1,2],[3,4]],[[5,6],[7,8]]];
>
> Somehow I find it surprising that this copies the whole array.
> arr[] = arr2;
I would use the following feature (from ref):
Array Setting
If a slice operator appears as the lvalue of an assignment expression, and the type of the rvalue is the same as the element type of the lvalue, then the lvalue's array contents are set to the rvalue.
int[3] s;
int* p;
s[] = 3; // same as s[0] = 3, s[1] = 3, s[2] = 3
p[0..2] = 3; // same as p[0] = 3, p[1] = 3
Using this, one could fill a multidimensional array by setting, so to say, from inside to outside. This is actually a variant of "(cast(T[n1*n2*n3])arr)[] = e;" that bearophile proposed, but it does not need any low-level hack:
void main () {
int[2][2][2] arr3;
int[2][2] arr2;
int[2] arr1;
arr1[] = 1;
arr2[] = arr1;
arr3[] = arr2;
assert(arr3 == [[[1, 1], [1, 1]], [[1, 1], [1, 1]]]);
}
I find the syntax somewhat wrong, would prefere it explicit like:
arr.fill(element);
or
arrayFill(arr, element);
How does this method perform? would you be kind enough to include it in your tests, %u? Even if it's slightly slower than "(cast(int[n1*n2*n3])arr)[] = e;", I would use it because I find it cleaner.
Is D reflexive enough to know at runtime the number of dimensions of an array and their sizes, and write a generic
arrayDeepFill(arr, element);
where element is the "terminal" value? Or maybe
arrayDeepFill(arr, element, [sizes]);
Denis
-- -- -- -- -- -- --
vit esse estrany ☣
spir.wikidot.com
More information about the Digitalmars-d-learn
mailing list