这个for循环不应该有错误吗?

Shouldn't there be an error in this for loop?

我正在阅读我的数据结构书籍,发现一些代码不适合我。我认为我对 for 循环的想法是错误的。有人可以帮忙吗?

void percolateDown(int hole){

    int child;
    Comparable tmp = array[hole];
     // my problem is that child is not initialized to a value until inside for loop how is hole = child possible! 
    for(; hole * 2 <= currentSize; hole = child){
          child = hole * 2;  
         //code that does percolate up
    }

    array[hole] = tmp; 
}

这段代码是对的我只是去掉了里面不需要的代码。您可能猜到了,但它是一种在堆中向下渗透的方法。

我的问题是 child 直到在 for 循环内才被赋予一个值,那么 for 循环如何在其中声明 hole = child?

我的假设是 for 循环中的所有内容都在 运行 之前或第一次迭代时。

for 循环的最后一部分仅在循环完成其第一次迭代后执行。因此,它首先设置child,然后将hole分配给child。

任何 for 形式的循环:

for (A; B; C) {
    ....
}

等同于以下形式的 while 循环:

{
    A;
    while (B) {
        ....
        C;
    };
}

因此,您可以看到循环体在 'increment' 部分之前执行(本例中为 C)。

hole = child赋值是在循环体执行完之后执行的,所以在执行的时候,child已经赋值了。

对于第一个近似值,循环等效于:

int child;
while (hole * 2 <= currentSize)
{
    child = hole * 2;
    hole = child;
}

(这是第一个近似值,因为显示的音译无法捕获 breakcontinue 的行为 — 但您的代码无论如何都没有这些。)

您可以通过简单地使用 hole *= 2; 作为循环体来避免 child

[stmt.for] 中的 C++11 §6.5.3/1:

The for statement

        for ( for-init-statement conditionopt; expressionopt ) statement

is equivalent to

        {
        for-init-statement
        while ( condition ) {
                statement
                expression ;
                }
        }

except that names declared in the for-init-statement are in the same declarative-region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition.

hole = child 更新直到 for 循环体之后才执行。

是的,在 Stack Overflow markdown 中格式化它是一件很痛苦的事情。显然对于标准的编辑来说也是如此(我认为这是用 LaTeX 或类似的东西编写的),因为最后 statement, expressioncondition 缺少斜体。我在引用中添加了它。