如何在一个循环内只运行一次没有外部标志的代码? [英] How to run code inside a loop only once without external flag?
问题描述
我想检查循环中的条件,并在第一次遇到时执行一段代码。之后,循环可能重复,但块应该被忽略。有这样的模式吗?当然,很容易在循环外声明一个标志。但我对一个完全生活在循环中的方法感兴趣。
I want to check a condition inside a loop and execute a block of code when it's first met. After that, the loop might repeat but the block should be ignored. Is there a pattern for that? Of course it's easy to declare a flag outside of the loop. But I I'm interested in an approach that completely lives inside the loop.
这个例子不是我想要的。有没有办法摆脱循环外的定义?
This example is not what I want. Is there a way to get rid of the definition outside of the loop?
bool flag = true;
for (;;) {
if (someCondition() && flag) {
// code that runs only once
flag = false;
}
// code that runs every time
}
推荐答案
这是相当hacky,但正如你所说的应用程序主循环,我认为它是一个一次调用函数,所以以下应该工作:
It's fairly hacky, but as you said it's the application main loop, I assume it's in a called-once function, so the following should work:
struct RunOnce {
template <typename T>
RunOnce(T &&f) { f(); }
};
:::
while(true)
{
:::
static RunOnce a([]() { your_code });
:::
static RunOnce b([]() { more_once_only_code });
:::
}
这篇关于如何在一个循环内只运行一次没有外部标志的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!