if 语句代替 while 循环
If statement(s) in lieu of a while loop
这个问题很奇怪,但是我有一个朋友问是否有可能,我无法给他答案。是否可以使用 if 语句编写以下 while 循环?
while (!x.empty() && !y.empty()){}
我在想,如果你有一个嵌套的 if 语句来设置一个标志,你可以使用 while-loop 绕过?还有其他想法吗?
对不起,这个愚蠢的问题。
您可以在循环中使用break
语句while
if-else 语句
while (1)
{
if (!x.empty() && !y.empty())
{
// do something;
}
else break;
}
有点。你可以用递归函数调用来做到这一点。 比如:
void whileLoop(){
if(!(!x.empty() && !y.empty())){
return;
}
//Code to run in loop here
whileLoop();
}
当您想要运行循环时,您将调用该函数。 请注意在原始循环中检查的条件前面的not符号; 好像条件不再为真,循环代码就不会运行。
另一种方式:递归
#include <stack>
#include <boost/hof.hpp>
int main()
{
extern std::stack<int> get();
auto x = get();
auto y = get();
auto f = boost::hof::fix([&](auto self)
{
if (!x.empty() && !y.empty())
{
x.pop();
y.pop();
self();
}
return 0;
});
boost::hof::result<int>(f)();
}
https://godbolt.org/z/M-JkV2
不是直接的,而是不使用while
的另一种方式......一个很好的goto
声明..
int main()
{
....
start:
if(!x.empty() && !y.empty())
goto start;
....
}
您可以在代码可读性上妥协,并通过递归来实现这一点。请注意,这将使代码比需要的更复杂。递归需要比常规迭代代码更多的堆栈空间。我会做这样的事情——
//iterative
while (!x.empty() && !y.empty()) {
//do something
}
//recursive
void recursion(vector<int> x, vector<int> y){
if(!x.empty() && !y.empty()) {
//do something
//remove element from vector based on your condition
x.pop_back();
y.pop_back();
recursion(x, y);
}
}
递归的退出条件是任一向量为空。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入