Initializing a static array
Ali Çehreli
acehreli at yahoo.com
Thu Mar 8 23:07:16 PST 2012
On 03/08/2012 06:02 PM, Hugo Florentino wrote:
> What is the proper D syntax to initialize a static array with
> consecutive integers starting with 1?
One of many ways:
int[N] makeArray(size_t N)()
{
int[N] result;
foreach (int i, ref element; result) {
element = i;
}
return result;
}
void main()
{
assert(makeArray!4() == [ 0, 1, 2, 3 ]);
}
> I know I could simply use "for" like in C, but while reading the web
> documentation on arrays, I noticed the vector notation. According to the
> documentation, this code:
> T[] a, b;
> ...
> a[] = b[] + 4;
>
> is equivalent to this code:
> T[] a, b;
> ...
> for (size_t i = 0; i < a.length; i++) a[i] = b[i] + 4;
It should be possible to use a special type and keep state to achieve it
with the arraywise syntax but this task is natural for that syntax.
> I also tried using the array as an aggregate in a foreach statement:
> foreach(int i, int j, myarray) j = i + 1;
>
> However, it does not work this way because apparently the j variable
> seems to work only for reading, not for assigning. I wonder why this
> limitation in behavior, if according to the documentation:
>
> "If there are two variables declared, the first is said to be the index
> and the second is said to be the value [set to the elements of the
> array, one by one]"
>
> So if j refers to the value,
That's the problem. j does not refer to the element, it is a copy of it.
You must use the 'ref' keyword as in the code that I have shown above.
> Either way, please advice the recommended D way.
There are many ways of initializing a fixed-length array with
consecutive integers. Here is another one:
import std.algorithm;
import std.range;
void main()
{
int[4] array = array(iota(4));
assert(array == [ 0, 1, 2, 3 ]);
}
>
> Regards, Hugo
Ali
P.S. There is also the D.learn newsgroup where such threads are very
welcome at. :)
More information about the Digitalmars-d
mailing list