Never seen before C++ for loop

后端 未结 12 2115
独厮守ぢ
独厮守ぢ 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:26

    The condition of the for loop is in the middle - between the two semicolons ;.

    In C++ it is OK to put almost any expression as a condition: anything that evaluates to zero means false; non-zero means true.

    In your case, the condition is u--: when you convert to C#, simply add != 0:

    for (u = b.size(), v = b.back(); u-- != 0; v = p[v]) 
        b[u] = v; //                     ^^^^ HERE
    

提交回复
热议问题