[英]For loop with if(array[i + 1]) goes out of array bounds; how to loop to beginning?
我有一個數組和一個for
循環的if
語句,用於檢查i + 1
。 但是,在循環的最后一次迭代中,數組超出范圍。 發生這種情況時,我想循環回到數組的開頭。 循環回array[0]
的最佳方法是什么? 這是我的代碼:
int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);
for (int i = 0; i < array.Length; i++)
{
if (array[i + 1] != 0)
// Do something (obviously in this example, this will always occur)
{
}
我可以執行以下操作,但是這需要我復制代碼(並且其中的當前代碼非常龐大)。 有沒有更好的方法來執行以下操作?
int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);
for (int i = 0; i < array.Length; i++)
{
if (i != array.Length - 1)
{
if (array[i + 1] != 0)
// Do something (obviously in this example, this will always occur)
{
}
else
{
if (array[0] != 0)
// Do something (obviously in this example, this will always occur)
{
}
}
使用模數:
if(array[(i+1) % array.Length] != 0) {...}
這基本上將從(i + 1)減去(i + 1)<array.Length減去array.Length
for (int i = 0; i < array.Length; i++)
{
if ((i + 1 < array.Length && array[i + 1] != 0) || (i + 1 == array.Length && array[0] != 0))
// Do something (obviously in this example, this will always occur)
{
}
array[(i + 1) % array.Length]
應該在沒有太多痛苦的情況下完成技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.