【问题标题】:How to break out of a nested loop?如何跳出嵌套循环?
【发布时间】:2022-09-24 12:47:11
【问题描述】:

有没有办法在没有 if/else 条件的情况下打破每一层?

    #include <iostream>
    using namespace std;
    int main()
    {
        for (int i = 0; i < 20; i++)
        {
            while (true) 
            { 
                while (true) 
                { 
                    break; break; break; 
                } 
            }
        }
    
        cout << \"END\";
        return 0;
    }
  • 为什么在同一个循环中有 3 个中断?每个循环只需要 1 个。
  • 你可以使用goto,但你最好重新考虑你的设计。
  • 每当您发现自己处于这种情况时,要问的真正问题是:为什么我的逻辑如此复杂以至于需要类似的东西。这表明应该对事物进行分解和重构,以将逻辑简化到不再需要的程度。
  • 虽然上面只是一个例子,但我不同意。我对流控制很满意,而且事情通常需要 3 层,尤其是在游戏开发中……哎呀,一个简单的 2D 扫描需要两个……

标签: c++ break


【解决方案1】:

您可以将逻辑包装在函数或 lambda 中。

而不是break; break; break;(这不起作用)你可以return;

#include <iostream>
using namespace std;
int main()
{
    auto nested_loops = []
    {
        for (int i = 0; i < 20; i++)
        {
            while (true) 
            { 
                while (true) 
                { 
                    // Done with all the looping
                    return;
                } 
            }
        }
    };

    nested_loops();
    cout << "END";
    return 0;
}

或者(同样的效果,不同的风格)

#include <iostream>
using namespace std;
int main()
{
    [] {
        for (int i = 0; i < 20; i++)
        {
            while (true) 
            { 
                while (true) 
                { 
                    // Done with all the looping
                    return;
                } 
            }
        }
    } ();

    cout << "END";
    return 0;
}

【讨论】:

  • 你可以做[]{ ... }(); 然后你不需要给它一个名字
  • @Slava 是的!我辩论过这种风格。或者std::invoke( []{...} );如果你想知道立即地lambda 将立即被调用,样式会有所不同。
【解决方案2】:

如果你想break个人环形,那么你可以使用break来尊重他们环形.

将太多或单个 break 放在一个环形, 只会break环形它在其中。


#include <iostream>
using namespace std;
int main()
{
    [] {
        for (int i = 0; i < 20; i++)
        {
            while (true) 
            { 
                while (true) 
                { 
                    break;
                } 
                break;
            }
            break;
        }
    } ();

    cout << "END";
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 2019-04-19
    • 2016-04-08
    • 1970-01-01
    • 2014-06-28
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多