我有一個多維陣列要遍歷,但是這個陣列的維數是一個變數,它可以是 2 或 10 甚至更多,例如當維數等于 2 時,我必須像這樣遍歷它:
for (int i=0; i<size[0]; i)
for (int j=0; j<size[1]; j)
// do something for arr[i * size[1] j];
對于 3 維 arr:
for (int i=0; i<size[0]; i)
for (int j=0; j<size[1]; j)
for (int k=0; k<size[2]; k)
// do something for arr[i * size[1] * size[2] j * size[2] k];
如何以可以處理可變維度的有效方式實作它?
uj5u.com熱心網友回復:
從評論中跟進這次對話:
或者,有一個索引陣列,并增加底部的索引,當它達到適當的大小時,將其重置為 0 并增加下一個索引(依此類推)。可能會在陣列中維護一個索引,這樣您就不會在每次迭代時重新計算偏移量。
謝謝@PaulHankin,您的解決方案似乎是我正在尋找的。通過維護一個索引陣列,如何真正實作它?
您需要的是一組索引,以及每個索引的一組大小,以便您知道何時翻轉。并且您需要知道何時超出了整個結構的最后一個索引。
在偽代碼中,是這樣的:
numDimensions = 3 // the number of dimensions
totalSize := size[0] * size[1] * size[2] // etc, the size of the whole structure
arrayIndex := 0
// here we're assuming that size and dimensionalIndex are indexed the same way
// initialized to 0, least significant digit at index 0
dimensionalIndex := Array(numDimensions)
while (arrayIndex < totalSize)
//
// Access arr[arrayIndex]
// arrayIndex should be equal to
// dimensionalIndex[0] dimensionalIndex[1] * size[0] dimensionalIndex[2] * size[0] * size[1], etc
//
// Increment the array counter
arrayIndex
// Increment the dimensional counters (which map to your i, j, k, etc)
dimensionalIndex[0] = 1
for (indexIndex = 0; indexIndex < numDimensions; indexIndex ):
// If one of the dimensions is exceeded, set it to 0 and increment the next one
if (dimensionIndex[indexIndex] >= size[indexIndex]) and (indexIndex < numDimensions-1):
dimensionIndex[indexIndex 1]
dimensionIndex[indexIndex] = 0
end if
end for
end while
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520457.html
標籤:算法数据结构
上一篇:Dijkstras演算法在有向圖中的最短路徑,找到到達目標頂點的最后一個節點
下一篇:使用遞回生成所有子序列
