4
我想做一個循環賽陣列。如果我要在一個循環中爲這個數組提供一堆值,並且我打到數組的末尾(假設它的長度爲10),那麼我將如何循環到第一個索引?在C中的循環賽陣列#
我想做一個循環賽陣列。如果我要在一個循環中爲這個數組提供一堆值,並且我打到數組的末尾(假設它的長度爲10),那麼我將如何循環到第一個索引?在C中的循環賽陣列#
循環時,用模塊化代數計算數組索引:
myArray[index % myArray.Length]
樣品
int[] myArray = new int[10];
// Round robin feeding; trying to put 0, 1, .. 13 into int[10]:
for (int i = 0; i < 14; ++i) // note 14 > 10
myArray[i % myArray.Length] = i; // i % myArray.Length - modular arithmetics
// Test
// 10, 11, 12, 13, 4, 5, 6, 7, 8, 9
// note that first 4 values (10, 11, 12, 13) are overriden
Console.Write(String.Join(", ", myArray));
非常好。簡單而優雅。謝謝。 – beardedeagle
你的意思是一個圓形隊列? – Dai
*模塊化*代數應該幫助你:'myArray [index%myArray.Length];' –
谷歌循環緩衝區應該有所幫助。 – Warty