简体   繁体   中英

C++ Data Structure to Find Neighbouring Values in Multidimensional Array

I have a project where I read in an array that has 1 or more dimensions, and for this project I need to be able to determine a given element's neighbours quickly. I do not know the dimensionality ahead of time, and I likewise do not know the size of the dimensions ahead of time. What would be the best C++ data structure to store this data in? A colleague recommended a vector of vectors of vectors of . . ., but that seems incredibly unwieldy.

If you know the address of which element you need the neighbors for, could you just do pointer arithmetic to find out the neighbors. For example, if p is the location of the element, then p-- is the left neighbor and p++ is the right neighbor.

Think your multidimensional array as a 1D array. Let the dimension of the array is d1 * d2 * ....* dn

Then allocate memory for a 1D array, say A of size d1 * d2 * ....* dn . For example,

int *A = new int[d1 * d2 * ....* dn];

If you need to store data in the [i1][i2]...[in] th index, then store in the following index:

A[i1 * (d2*d3*d4.. *dn) + i2 * (d3*d4*....dn) + ..... + in] 

Neighboring elements will be:

A[(i1 + 1) * (d2*d3*d4.. *dn) + i2 * (d3*d4*....dn) + ..... + in] 
A[(i1 - 1) * (d2*d3*d4.. *dn) + i2 * (d3*d4*....dn) + ..... + in] 

A[i1 * (d2*d3*d4.. *dn) + (i2 + 1) * (d3*d4*....dn) + ..... + in] 
A[i1 * (d2*d3*d4.. *dn) + (i2 - 1) * (d3*d4*....dn) + ..... + in] 

.............................
A[i1 * (d2*d3*d4.. *dn) + i2 * (d3*d4*....dn) + ..... + (in + 1)] 
A[i1 * (d2*d3*d4.. *dn) + i2 * (d3*d4*....dn) + ..... + (in - 1)] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM