如果语句c ++错误则中断

mik*_*ike 1 c++ for-loop if-statement break

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

这是一个用于线性探测功能的for-loop,它工作得很好.

//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;
           }
Run Code Online (Sandbox Code Playgroud)

所以我在二次探测函数中再次写了一个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;
        }
Run Code Online (Sandbox Code Playgroud)

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

error: 'break' statement not in loop or switch statement
Run Code Online (Sandbox Code Playgroud)

我真的很困惑,为什么它导致第二个错误,而线性探测是好的.谁有人解释为什么?

Sta*_*ght 5

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
    j = i^2;
Run Code Online (Sandbox Code Playgroud)

这是你的周期,因为你没有在它周围放置花括号.

修复很简单,把那些括号:

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

经验法则 - 当你使用cycle或if-statement时总是把花括号括起来,因为它可以帮助你不要犯这样的错误.