【问题标题】:Can I use “for … else” loop in C++? [duplicate]我可以在 C++ 中使用“for ... else”循环吗? [复制]
【发布时间】:2021-08-23 23:37:22
【问题描述】:

我是 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++ 中没有像 for ... else 循环这样的东西。你应该再次查阅你的教科书。这甚至不是远程有效的 C++ 代码。
  • 好的,谢谢@πάνταῥεῖ
  • 您需要检查if 中的循环条件(如果为假,则循环“失败”)或使用循环后检查的额外布尔变量。
  • 您可以编写在 C++ 中功能等效的代码,但看起来会有所不同
  • @Someprogrammerdude 好的。我可以试试这个过程

标签: c++ loops for-loop


【解决方案1】:

不,在 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 中也可以使用的其他替代方法是引入一个额外的布尔变量和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();
}

【讨论】:

  • 也许这是有效的方法,谢谢
【解决方案2】:

您可以实现类似的目标。只需添加一个分支来测试是否满足循环的退出条件。这是一个例子:

#include <cstdio>

int main() {
  for (int n = 2; n < 10; ++n) {
    int x = 2;
    for (; x < n; ++x) {
      if (n % x == 0) {
        std::printf("%d equals %d * %d\n", n, x, n / x);
        break;
      }
    }
    if (x == n)
      std::printf("%d is a prime number\n", n);
  }
}

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2020-11-26
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多