What's the best way to do a backwards loop in C/C#/C++?

后端 未结 14 2598
终归单人心
终归单人心 2020-11-28 01:39

I need to move backwards through an array, so I have code like this:

for (int i = myArray.Length - 1; i >= 0; i--)
{
    // Do something
    myArray[i] =          


        
相关标签:
14条回答
  • 2020-11-28 02:09

    I'd use the code in the original question, but if you really wanted to use foreach and have an integer index in C#:

    foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())
    {
        myArray[i] = 42; 
    }
    
    0 讨论(0)
  • 2020-11-28 02:10

    I prefer a while loop. It's more clear to me than decrementing i in the condition of a for loop

    int i = arrayLength;
    while(i)
    {
        i--;
        //do something with array[i]
    }
    
    0 讨论(0)
提交回复
热议问题