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

后端 未结 14 2704
终归单人心
终归单人心 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 01:59

    That's definitely the best way for any array whose length is a signed integral type. For arrays whose lengths are an unsigned integral type (e.g. an std::vector in C++), then you need to modify the end condition slightly:

    for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)
        // blah
    

    If you just said i >= 0, this is always true for an unsigned integer, so the loop will be an infinite loop.

提交回复
热议问题