如果语句c 错误,请打破

Break if statement c++ error

本文关键字:错误 语句 如果      更新时间:2023-10-16

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

这是我用于线性探测功能的循环,它的工作原理很好。

//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循环以处理Collision

//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;
    }
}

经验法则 - 当您使用循环或静态时,请始终放置卷曲牙套,因为它可以帮助您不犯此类错误。

,因为只有下面的语句是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(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2; 
    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

您没有在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;
    }
}

一个好的经验法则是将牙套放在任何循环主体周围,该循环主体不超过一条线长。许多人会建议您在以后的时间内添加更多的循环主体,甚至在单行周围放牙套。