Comments: Back to Basics: Two-Dimensional Arrays

The way I always do multidimensional arrays is to just do a very basic wrapper around a flat 1D array.

For example (written in D—opCall is basically the constructor, and opIndex is the subscript operator overload):

struct Float2D
{
    float[] data;
    size_t w,h;
    
    Float2D opCall(size_t w, size_t h)
    {
        Float2D result;
        result.data = new float[](w*h);
        result.w = w;
        result.h = h;
        return result;
    }
    
    float opIndex(size_t i, size_t j)
    {
        return data[i+w*j];
    }
}

Used like so:

auto array2d = Float2D(3,4);
writefln("Value 2 across, 1 down: %f", array2d[2,1]);

No idea how that'd be translated into Mozilla funny-buggers... :P

Posted by Daniel at December 6, 2008 12:02 AM
Post a comment









Remember personal info?