有没有其他选择可以打破?

Is there another alternative to break?

本文关键字:其他 选择 有没有      更新时间:2023-10-16

我对中断指令有问题;

事实上,就我而言,我在下面的计算代码示例中重现了我使用两个嵌套的 for 循环和 if 循环。

我希望当open_bound变量= 0时,完全退出循环,从而显示时间t的值。执行后,我看到显示时间 t = 0 而不是 3,我很难理解为什么。你能开导我吗?

有没有其他选择可以打破?(我不能使用 goto,而且我在真实代码中并行化这部分(

提前谢谢你

#include <iostream>
#include <vector>
using namespace std;
      
int main () {
    int numtracers = 1000;
    int save_t;
    double t;
     
    int open_bound = 0;
    int tau = 5;
    double int_step = 0.25;
     
    for (int i = 0; i < numtracers; i++) {
        // Variable to overwrite the successive positions of each particle
        vector <double> coord(2);
        coord[0] = 0.1;
        coord[1] = 0.2;
        int result_checkin;
        for(t=0; t<tau-1; t+=int_step) {
            save_t = t;
            // Function to check if coordinates are inside the domain well defined
            // result_checkin = check_out(coord);
            if (t == tau-2) result_checkin = 1;
            if (result_checkin == 1) { // Particle goes outside domain
if (open_bound == 0) {  
                    break;                         
                }
                else {
                    coord[0]+=0.1;
                    coord[1]+=0.1;                     
                }
            }
            else {
                coord[0]+=0.1;
                coord[1]+=0.1;
            }
        }
}
cout << save_t << endl;
    return 0;
}

好的,让我们首先回顾一下break语句的作用(不包括它在switch块中的使用(:它"打破"了最里面的封闭forwhiledo ... while循环。因此,这里不考虑if语句 - 它们也不是真正的循环,是吗。

因此,在您的主代码中,您实际上只有两个循环。你自己的break将退出最里面,立即跳到我在下面的代码中突出显示的点。添加额外的if ... break;代码,就像我所做的那样,将退出外部循环:

for (int i = 0; i < numtracers; i++) {
int open_bound = 0; // MUST HAVE HERE to parallelize this loop!
// Variable to overwrite the successive positions of each particle
vector <double> coord(2);
coord[0] = 0.1;
coord[1] = 0.2;
int result_checkin;
for(t=0; t<tau-1; t+=int_step) {
save_t = t;
// Function to check if coordinates are inside the domain well defined
// result_checkin = check_out(coord);
if (t == tau-2) result_checkin = 1;
if (result_checkin == 1) { // Particle goes outside domain
if (open_bound == 0) {  
break; // Exits the inner for loop and goes to the "-->HERE" line!               
}
else {
coord[0]+=0.1;
coord[1]+=0.1;                     
}
}
else {
coord[0]+=0.1;
coord[1]+=0.1;
}
}
// Your "break" exits the for loop and execution continues -->HERE
if (open_bound == 0) break; // This will (always) exit the outer loop!
}

这有帮助吗?请随时要求进一步解释!

编辑 - 关于循环并行化的说明:如果要并行化 外循环,那么只有当你在该循环内移动open_bound的声明/定义时,你才能这样做(正如我 在上面的代码中完成了(!如果您正在尝试,则无法并行化 修改和测试在循环之外声明的标量变量 范围。

退出所有想要的循环的替代方法是使用 bool 标志来决定何时强制循环终止。当您点击open_bound=0时,您可以先将标志设置为 false,然后中断。

检查以下内容以了解我的意思:

bool go = true;
for (int i = 0; go &&  CONDITION1; i++)
for (int j = 0; go &&  CONDITION2; j++)
for (int k = 0; go &&  CONDITION3; k++)
....
if(open_bound==0){
go = false;
break;
}

您的代码的工作版本在这里