if 语句代替 while 循环

If statement(s) in lieu of a while loop

本文关键字:while 循环 语句 if      更新时间:2023-10-16

这个问题很奇怪,但是我有一个朋友问是否有可能,我无法给他答案。是否可以使用 if 语句编写以下 while 循环?

while (!x.empty() && !y.empty()){}

我在想,如果你有一个嵌套的 if 语句来设置一个标志,你可以使用 while-loop 绕过?还有其他想法吗?

对不起,这个愚蠢的问题。

您可以在循环中使用break语句whileif-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);
} 
}

递归的退出条件是任一向量为空。