打破嵌套循环

时间:2018-03-15 12:14:34

标签: c++ loops nested break

如果我在x找到某些内容,我想打破内部循环并增加Matrix[x][y]的值,但如果我在y for loop中突破,它只会增加y loop的值1}}而不是x loop

int matrix[5][5]; //let's assume there are values inside
for(int i = 0; i < 5; i++)
   {
     for(int j = 0; j<5;j++)
      {
        int radius = 1;
        for(int x = radius - 1; x <= radius + i; x ++)
         {
          for(int y = radius -1; y <= radius +j; y++)
            {
               if((x+i) >= 0 && (y+j)>=0)
                 {
      //for example I find the number 45 in the matrix, then the search radius should be increased by 1 and start it over again.
                  if(matrix[x][y] == 45)
                     {
                       radius++;
                       break; // but if i break here the x value wont be changed
                      }

                  }
             }
          }
      }

1 个答案:

答案 0 :(得分:0)

非本地退出机制C ++提供了throw:

try {
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 3; ++y) {
            std::cout << x << ", " << y << std::endl;
            if(y == 1 && x == 3) throw true;
        }
    }
}
catch(bool) {}
std::cout << std::endl;

此外,您可以修改外部循环的变量,以便最终条件成立:

for(int x = 0; x < 10; ++x) {
    for(int y = 0; y < 3; ++y) {
        std::cout << x << ", " << y << std::endl;
        if(y == 1 && x == 3) {
            x = 10;
            break;
        }
    }
}
std::cout << std::endl;

(或者,如果您不想修改变量本身,比如说,它不是循环的本地变量,之后您需要它的值,请在循环条件中添加一个标记:

bool continueOuter{true};
for(int x = 0; continueOuter && x < 10; ++x) {
    for(int y = 0; y < 3; ++y) {
        std::cout << x << ", " << y << std::endl;
        if(y == 1 && x == 3) {
            continueOuter = false;
            break;
        }
    }
}