如何在没有外部标志的情况下只在循环中运行一次代码
How to run code inside a loop only once without external flag?
我想检查循环中的条件,并在第一次满足条件时执行代码块。之后,循环可能会重复,但应该忽略该块。这有模式吗?当然,在循环之外声明一个标志是很容易的。但我对一种完全生活在循环中的方法感兴趣。
这个例子不是我想要的。有没有办法摆脱循环之外的定义?
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行)
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 尝试用java代码编译和运行c++代码
- 不同/较旧的处理器运行c++代码的方式是否不同
- 无法在 geany 上运行代码。无法执行构建命令
- 运行代码时,c++ 会终止进程
- 编译多个C++文件.调用二进制文件以运行代码
- 分段故障 运行C++代码时出现 SIGSEGV
- 如何分析在 Windows 上运行C++代码?
- 编译器资源管理器(godbolt)如何安全地运行代码?
- 如何在 vim (windows) 中编译和运行 c++ 代码
- 无法在 Visual Studio 代码中生成和运行 C++ 代码
- 连续运行C++代码和 Python 代码
- 在静态初始化期间运行代码
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 如何在Visual Studio Code的终端内运行C++代码?
- 在注入的 Dll 的 DllMain 中运行代码导致注入超时
- 并行和顺序运行代码时会产生不同的结果
- 运行代码时C++错误
- 在 CortexM0 中从 RAM 运行代码时出现硬故障