中断 if 语句 c++ 错误

Break if statement c++ error

我正在编写线性和二次探测哈希 table 程序。

这是我用于线性探测功能的 for 循环,它工作得非常好。

//when there's a collision increase i by 1 until finding empty slot
       for(i = (hashVal % tableSize+1) % tableSize; i <tableSize; i++)
           if(a[i] == -1){
               a[i] = hashVal;
               break;
           }

所以我又在二次探测函数中写了一个for循环来处理碰撞

//when there's a collision increase i by i^2
    j = 0;

    for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
        j = i^2;
        if(a[j] == -1){
            a[j] = hashVal;
            break;
        }

但是当我编译二次探测时,出现了这个错误

error: 'break' statement not in loop or switch statement

我真的很困惑为什么它在第二个中导致错误,而在线性探测中却很好。谁能解释为什么?

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
    j = i^2;

这是你的循环,因为你没有用大括号括起来。

修复很简单,放上那些大括号:

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
{
    j = i^2;
    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

经验法则 - 在使用循环或 if 语句时始终使用花括号,因为它可以帮助您避免出现此类错误。

您没有在 for 语句的正文两边加上大括号。这在第一个示例中有效,因为正文只是 if 语句,但在您的第二个示例中,只有 j = i^2; 被解析为 for 的一部分。代码相当于:

//when there's a collision increase i by i^2
j = 0;

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2;
}

if(a[j] == -1){
    a[j] = hashVal;
    break;
}

您可以通过在正确的位置添加大括号来解决此问题:

//when there's a collision increase i by i^2
j = 0;

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2;
    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

一个好的经验法则是将大括号放在任何超过一行长的循环体周围。许多人甚至会建议将大括号放在单行周围,以防您以后想向循环体添加更多内容。

因为只有紧接着的语句才是for循环体,所以

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
    j = i^2; // the body of for loop

// not for loop body from here (note the correct indent position)
if(a[j] == -1){
    a[j] = hashVal;
    break;
}

对于您的第一个代码示例,整个 if 语句是 for 循环体,因此它工作正常。

要修复您的代码,您可以使用大括号使其成为 compound statement,它可能包含多个语句。

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2; 

    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}