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

dan*_*jar 11 c++ flags loops design-patterns control-flow

我想检查一个循环内的条件,并在第一次遇到时执行一段代码.之后,循环可能会重复,但应忽略该块.那有什么模式吗?当然,在循环之外声明一个标志很容易.但是我对一种完全存在于循环中的方法感兴趣.

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

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

Rei*_*ica 11

这是相当hacky,但正如你所说它是应用程序主循环,我认为它是在一次调用函数中,所以以下应该工作:

struct RunOnce {
  template <typename T>
  RunOnce(T &&f) { f(); }
};

:::

while(true)
{
  :::

  static RunOnce a([]() { your_code });

  :::

  static RunOnce b([]() { more_once_only_code });

  :::
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*son 9

对于一个不太复杂的Mobius版本的答案:

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.
}
Run Code Online (Sandbox Code Playgroud)

你也可以++在bool上写这个,但这显然已被弃用了.