opIndexMember

sighoya sighoya at gmail.com
Sun Dec 27 17:34:44 UTC 2020


On Sunday, 27 December 2020 at 14:46:43 UTC, claptrap wrote:
> In some cases a structure of arrays is more desirable than an 
> array of structs, usually for performance reasons, but maybe 
> you want tight packing or something else, so I have been 
> thinking a while about proposing the following...


What about this:

```
import std.math;
struct Struct
{
     float[] x;
     float[] y;
     float[] z;

     this(float[] x, float[] y, float[] z)
     {
         this.x=x;
         this.y=y;
         this.z=z;
     }
     float[3] opIndex(int index)
     {
         return [x[index],y[index],z[index]];
     }
}



float x(float[3] array)
{
     return array[0];
}


float y(float[3] array)
{
     return array[1];
}

float z(float[3] array)
{
     return array[2];
}

float magnitude(float[3] array)
{
     return sqrt(sqr(array[0])+sqr(array[1])+sqr(array[2]));
}

float sqr(float x)
{
     return x*x;
}

int main()
{
     import std.stdio;
     Struct s = Struct([1,2],[3,4],[5,6]);
     writeln(s[0].x);
     writeln(s[0].y);
     writeln(s[0].z);
     writeln(s[0].magnitude());
     return 0;

}

```



More information about the Digitalmars-d mailing list