简体   繁体   English

C ++数据结构以查找多维数组中的相邻值

[英]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. 我有一个项目,在其中读取具有1个或多个维度的数组,为此项目,我需要能够快速确定给定元素的邻居。 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? 存储该数据的最佳C ++数据结构是什么? 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. 例如,如果p是元素的位置,则p--是左邻居,而p ++是右邻居。

Think your multidimensional array as a 1D array. 将多维数组视为一维数组。 Let the dimension of the array is d1 * d2 * ....* dn 令数组的维数为d1 * d2 * ....* dn

Then allocate memory for a 1D array, say A of size d1 * d2 * ....* dn . 然后为一数组分配内存,例如大小为d1 * d2 * ....* dn A 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: 如果需要将数据存储在第[i1][i2]...[in]个索引中,请存储在以下索引中:

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)] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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