arrays && functions && pointers
Daniel Keep
daniel.keep.lists at gmail.com
Sun Jun 18 23:38:43 PDT 2006
Hasan Aljudy wrote:
>
>
> Jarrett Billingsley wrote:
>> "Jarrett Billingsley" <kb3ctd2 at yahoo.com> wrote in message
>> news:e751ri$2709$1 at digitaldaemon.com...
>>
>>
>>>> btw. How do I reset all the data of a rectangular array?
>>>> something like:
>>>> tiles[][]=0;
>>
>>
>> Damn news client. Ctrl + Enter posts, apparently.
>>
>> I assume your array is of a static size (thus making it a rectangular
>> array). You can do this:
>>
>> foreach(/* auto */ a; tiles)
>> a[] = 0;
>>
>> (I just put the /* auto */ in there to let me know when I'm using the
>> dirty, nonobvious foreach index type inference)
>>
>> Or, and this is a little hackish, but you can take advantage of the
>> layout of rectangular arrays, which is a single block of memory:
>>
>> ((cast(TILE*)tiles.ptr)[0 .. TILEW * TILEH])[] = 0;
>>
>> Basically, you're converting the rectangular array type into a linear
>> array type, and setting all those elements to 0. I would imagine this
>> would be somewhat faster, since it's doing one block set, rather than
>> one block for each row.
>>
>
>
> This won't work if the array is dynamically allocated.
>
> Dynamic 2D arrays in are not exactly c-style rectangular arrays; they
> are arrays of pointers to arrays of pointers. In C# they call this
> "jagged arrays".
>
> see:
> http://www.digitalmars.com/d/arrays.html
> scroll down to "Rectangular Arrays"
> <quote>
> (Dynamic arrays are implemented as pointers to the array data.) Since
> the arrays can have varying sizes (being dynamically sized), this is
> sometimes called "jagged" arrays. Even worse for optimizing the code,
> the array rows can sometimes point to each other! Fortunately, D static
> arrays, while using the same syntax, are implemented as a fixed
> rectangular layout
> </quote>
>
>> I assume your array is of a static size
>
> Is there a way in D to test for this? anything like:
> assert( isStaticallyAllocated( tiles ) );
> would be nice in this case, but I don't think it's possible.
>
> I would rather use a one-dimensional array and treat it as if it were
> rectangular. Maybe a little template magic can help ease this task.
>
What I did when I needed this was to make a small templated struct that
implemented opIndex and opIndexAssign, which took care of the
two-dimensional lookups for me. The code to do this is pretty much
trivial, but this way you can add bounds checking, and since the code is
so short, `-release -O -inline` should expand the function out for you.
A nice advantage to using a struct (or even a class) is that you can
then go and do all sorts of evil things like clipping, strides and other
fun things.
-- Daniel
--
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d-learn
mailing list