How to break out of nested loops?

前端 未结 15 2442
北荒
北荒 2020-11-27 11:21

If I use a break statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will

相关标签:
15条回答
  • 2020-11-27 12:10

    One way is to put all the nested loops into a function and return from the inner most loop incase of a need to break out of all loops.

    function() 
    {    
      for(int i=0; i<1000; i++)
      {
       for(int j=0; j<1000;j++)
       {
          if (condition)
            return;
       }
      }    
    }
    
    0 讨论(0)
  • 2020-11-27 12:10

    You'll need a boolean variable, if you want it readable:

    bool broke = false;
    for(int i = 0; i < 1000; i++) {
      for(int j = 0; j < 1000; i++) {
        if (condition) {
          broke = true;
          break;
        }
      }
      if (broke)
        break;
    }
    

    If you want it less readable you can join the boolean evaluation:

    bool broke = false;
    for(int i = 0; i < 1000 && !broke; i++) {
      for(int j = 0; j < 1000; i++) {
        if (condition) {
          broke = true;
          break;
        }
      }
    }
    

    As an ultimate way you can invalidate the initial loop:

    for(int i = 0; i < size; i++) {
      for(int j = 0; j < 1000; i++) {
        if (condition) {
          i = size;
          break;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-27 12:10
    int i = 0, j= 0;
    
    for(i;i< 1000; i++){    
        for(j; j< 1000; j++){
            if(condition){
                i = j = 1001;
                break;
            }
        }
    }
    

    Will break both the loops.

    0 讨论(0)
  • 2020-11-27 12:11
    bool stop = false;
    for (int i = 0; (i < 1000) && !stop; i++)
    {
        for (int j = 0; (j < 1000) && !stop; j++)
        {
            if (condition)
                stop = true;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 12:11

    Caution: This answer shows a truly obscure construction.

    If you are using GCC, check out this library. Like in PHP, break can accept the number of nested loops you want to exit. You can write something like this:

    for(int i = 0; i < 1000; i++) {
       for(int j = 0; j < 1000; j++) {
           if(condition) {
                // break two nested enclosing loops
                break(2);
           }
       }
    }
    
    0 讨论(0)
  • 2020-11-27 12:15
    for(int i = 0; i < 1000; i++) {
       for(int j = 0; j < 1000; i++) {
           if(condition) {
                goto end;
       }
    } 
    
    end:
    
    0 讨论(0)
提交回复
热议问题