Multidimensional array
Ali Çehreli
acehreli at yahoo.com
Sat Jul 6 22:06:00 PDT 2013
On 07/05/2013 09:00 PM, Oleksiy wrote:
> Look like there is a consequence - can't perform array-wise operations
> on multidimensional arrays?
I don't want to accept that conclusion because there is no such thing as
a multidimensional array in D. :) (To be fair, they don't exist in C and
C++.)
What we call a multidimensional array is achieved by defining arrays
where the elements are arrays themselves. But D does not know or care
about that. As a result, array-wise operations apply only to the
outermost layer of so-called multidimensional arrays.
Let's have the following two-dimensional arrays:
int[][] a;
int[][] b;
int[][] c;
We can still use the array-wise syntax:
c[] = a[] OP b[];
Let's think about what can appear as an operator instead of OP above...
Since the elements of the outer layers of the array are themselves
arrays (more correctly, slices), then OP must be an operator that can
have two slices on its side. The concatenation operators comes to mind
but I could not make it work:
c[] = a[] ~ b[];
That should have the same effect as concatenating the corresponding
elements of a and b and assigning the result to c.
It does not work.
> And that's why a need to touch the elements
> themselves, like in the example you provided:
>
> import std.stdio;
>>
>> void main()
>> {
>> dchar[3][5] arr = '.';
>>
>> foreach (ref e; arr) {
>> e[2] = '!';
>> }
>>
>> writeln(arr);
>> }
That example is doing what you needed to do: Assign a specific value to
a column of the multidimensional array. Unfortunately, there is no
special syntax in D to do that.
> Also huge thank you for your book - holy grail for beginners.
Thank you very much for the kind words; makes me very happy.
> --------------------------------
>> But this doesn't compile:
>>
>> char[3][5] arr = [ '.', '.', '.' ];
>>
>> Error: mismatched array lengths, 15 and 3
>>
>> I see that as a bug but can't be sure.
>
> Others seem to agree with you, will you be submitting this bug?
As TommiT did, it is better to try a code that has a fixed-length array
on the right-hand side:
void main()
{
int[3] values = [ 1, 2, 3 ];
int[3][2] a = values;
}
Error: mismatched array lengths, 6 and 3
Reported:
http://d.puremagic.com/issues/show_bug.cgi?id=10562
Ali
More information about the Digitalmars-d-learn
mailing list