我是 C++ 新手。有什么办法可以使用“for...else”方法吗?
我来自 python 背景,有一个方法叫做 for...else 循环
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print( n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
C++ 中有没有类似于 Python 中的“for...else”循环的过程?
不,在 C++ 中没有什么等同于 Python 的 for-else。
有几种方法可以转换函数。我将使用一个更简单的示例:
for i in range(a, b):
if condition(i):
break
else:
not_found()
最接近的转换可以使用goto
来实现,但是你可能会发现有些同事可能会反对(因为goto是“邪恶的”和可怕的):
for (int i = a; i < b; i++) {
if (condition(i)) {
goto found;
}
}
not_found();
found:;
在 Python 中也可以使用的其他替代方法是引入一个额外的 bool 变量和 if
:
bool found = false;
for (int i = a; i < b; i++) {
if (condition(i)) {
found = true;
break;
}
}
if (!found) {
not_found();
}
或者将整个事情封装在一个函数中,我认为这是 Python 和 C++ 中最广泛接受的替代方法。
void function()
{
for (int i = a; i < b; i++) {
if (condition(i)) {
return;
}
}
not_found();
}