简体   繁体   English

暂停和恢复循环C ++

[英]Pausing and resuming for loop c++

I would like to know is there a way to to return back to the last iteration of the for loop, after the break and continue from there, for ex.: 我想知道是否有一种方法可以在中断之后返回到for循环的最后一次迭代,然后从那里继续执行,例如:

void loop()
{
    for (n ; n<10; n++)
        if (n=5) { break; }
}

// code

loop();  // should start from 6 ...

Write a class: 编写一个类:

class my_loop
{
    int i;
public:
    my_loop(): i(0) {}
    void loop_some()
    {
        while (i != some_limit)
            ...
    }
};

The instance of the class contains the necessary info for running the loop. 该类的实例包含运行循环所需的信息。 You can return from loop_some() and call it again when necessary. 您可以从loop_some()返回并在必要时再次调用它。

Declare n as a static variable, ( static int n=0 ) so it retains its value and use continue instead of break . n声明为静态变量( static int n=0 ),以便保留其值,并使用continue而不是break

void loop()
 {
      static int n=0;
      for (; n<10; n++){

          if (n==5  ){  

             cout<<"  n = 5   "; 
             continue; 
          }

            cout<<""<<n<<" ";
       }

}

Output: 输出:

0 1 2 3 4   n = 5   6 7 8 9
 Press any key to continue

What i could think of would be to use goto to to leave and go back into your loop. 我能想到的是使用goto离开并返回您的循环。 But you should try to avoid this because it leads to very difficult readable code. 但是您应该尝试避免这种情况,因为它会导致很难读取的代码。 Here are two links which could help to decide: 这里有两个链接可以帮助您确定:

Use goto or not 是否使用goto

Statements and flow control 报表和流程控制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM