如何在没有外部标志的情况下只在循环中运行一次代码

How to run code inside a loop only once without external flag?

本文关键字:运行 代码 一次 循环 外部 标志 情况下      更新时间:2023-10-16

我想检查循环中的条件,并在第一次满足条件时执行代码块。之后,循环可能会重复,但应该忽略该块。这有模式吗?当然,在循环之外声明一个标志是很容易的。但我对一种完全生活在循环中的方法感兴趣。

这个例子不是我想要的。有没有办法摆脱循环之外的定义?

bool flag = true;
for (;;) {
    if (someCondition() && flag) {
        // code that runs only once
        flag = false;
    }        
    // code that runs every time
}

它相当粗糙,但正如您所说的,它是应用程序主循环,我假设它在一个调用一次的函数中,因此以下内容应该有效:

struct RunOnce {
  template <typename T>
  RunOnce(T &&f) { f(); }
};
:::
while(true)
{
  :::
  static RunOnce a([]() { your_code });
  :::
  static RunOnce b([]() { more_once_only_code });
  :::
}

对于莫比乌斯答案的一个不那么复杂的版本:

while(true)
{
  // some code that executes every time
  for(static bool first = true;first;first=false)
  {
    // some code that executes only once
  }
  // some more code that executes every time.
}

您也可以在bool上使用++来编写这篇文章,但这显然是不推荐的。

写这篇文章的一种可能更干净的方法,尽管仍然有一个变量,如下

while(true){
   static uint64_t c;
   // some code that executes every time
   if(c++ == 0){
      // some code that executes only once
   }
   // some more code that executes every time.
 }

static允许您在循环中声明变量,IMHO看起来更干净。如果每次执行的代码都进行了一些可测试的更改,那么您可以去掉这个变量并这样写:

while(true){
   // some code that executes every time
   if(STATE_YOUR_LOOP_CHANGES == INITIAL_STATE){
      // some code that executes only once
   }
   // some more code that executes every time.
 }
#include <iostream>
using namespace std;
int main()
{
    int fav_num = 0;
    while (true)
    {
    if ( fav_num == 0)
    {
        cout <<"This will only run if variable fav_number is = 0!"<<endl;
    }
    cout <<"Please give me your favorite number."<<endl;
    cout <<"Enter Here: ";
    cin >>fav_num;
    cout <<"Now the value of variable fav_num is equal to "<<fav_num<<" and not 0 so, the if statement above won't run again."<<endl;
    }
    
    return 0;
}

输出

This will only run if variable fav_number is = 0!
Please give me your favorite number.
Enter Here: 1
Now the value of variable fav_num is equal to 1 and not 0 so, the "if statement" above won't run again.

如果您知道只想运行一次这个循环,为什么不使用break作为循环中的最后一条语句呢。

1    while(true)
2    {
3        if(someCondition())
4        {
5            // code that runs only once
6            // ...
7          // Should change the value so that this condition must return false from next execution.
8        }        
9    
10        // code that runs every time
11        // ...
12    }

如果您希望代码中没有任何外部标志,那么您需要更改条件的最后一条语句中条件的值。(代码片段中的第7行)