【问题标题】:Break if statement c++ error [closed]中断if语句c ++错误[关闭]
【发布时间】:2016-12-01 09:06:57
【问题描述】:

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

这是我用于线性探测功能的 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 循环之后缺少花括号。

标签: c++ if-statement for-loop break


【解决方案1】:
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 语句时,请务必使用大括号,因为它可以帮助您避免出现此类错误。

【讨论】:

    【解决方案2】:

    因为只有紧随其后的语句是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;
        }
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 1970-01-01
        • 2012-12-20
        相关资源
        最近更新 更多