Never seen before C++ for loop

后端 未结 12 2112
独厮守ぢ
独厮守ぢ 2020-12-07 10:58

I was converting a C++ algorithm to C#. I came across this for loop:

for (u = b.size(), v = b.back(); u--; v = p[v]) 
b[u] = v;

It gives no

12条回答
  •  臣服心动
    2020-12-07 11:49

    Lots of accurate answers, but I think it's worth writing out the equivalent while loop.

    for (u = b.size(), v = b.back(); u--; v = p[v]) 
       b[u] = v;
    

    Is equivalent to:

    u = b.size();
    v = b.back();
    while(u--) {
       b[u] = v;
       v = p[v];
    }
    

    You might consider refactoring to the while() format as you translate to C#. In my opinion it is clearer, less of a trap for new programmers, and equally efficient.

    As others have pointed out -- but to make my answer complete -- to make it work in C# you would need to change while(u--) to while(u-- != 0).

    ... or while(u-- >0) just in case u starts off negative. (OK, b.size() will never be negative -- but consider a general case where perhaps something else initialised u).

    Or, to make it even clearer:

    u = b.size();
    v = b.back();
    while(u>0) {
       u--;
       b[u] = v;
       v = p[v];
    }
    

    It's better to be clear than to be terse.

提交回复
热议问题