a struct as an multidimensional array index
z
z at z.com
Fri Jun 10 15:13:02 UTC 2022
On Friday, 10 June 2022 at 08:08:45 UTC, Chris Katko wrote:
> Is it somehow possible to use a struct as a [multidimensional]
> array index:
>
> ````D
>
> struct indexedPair
> {
> size_t x, y;
> }
>
> bool isMapPassable[100][100];
> auto p = indexedPair(50, 50);
>
> if(isMapPassable[p]) return true;
>
> ````
>
> Probably not, but I'm curious.
AFAIK no.
I admit it's an area D could improve on, it creates a lot of
confusion because of the ordering and the lack of an integrated
solution.
(arrays of arrays has different order for declaration and
addressing, and declaring array of arrays has different order
depending on how you declare it and wether it's static or dynamic
array, *oof*)
To give you an idea of the situation :
```D
int[3][1] a;//one array of 3 int
writeln(a[0][2]);//first "column", third "row"
```
One thing you could do however is make the array accept a
multidimensional argument through operator overloading(opIndex)
if it is the only array from a struct, but that gets unviable
when you have multiple arrays that would benefit from it.
To summarize, there does not appear to be an easy solution that
has no drawbacks. I'd recommend saving yourself the trouble of
array of arrays(of arrays?) and using a single array of length
x*y with a function to index into it `(x+(xlength*y)` or `(
(x+(xlength*y)) + ((xlength*ylength)*z)) )` if that is desirable.
More information about the Digitalmars-d-learn
mailing list