首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何突破嵌套循环?

如何突破嵌套循环?
EN

Stack Overflow用户
提问于 2022-09-02 01:32:37
回答 3查看 107关注 0票数 1

有没有任何方法可以打破这一点,而不对每一层的if/else条件?

代码语言:javascript
复制
#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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-09-02 01:36:03

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

而不是break; break; break; (这是行不通的),您可以return;

代码语言:javascript
复制
#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;
}

或(相同的效果,不同的风格)

代码语言:javascript
复制
#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;
}
票数 3
EN

Stack Overflow用户

发布于 2022-09-02 02:05:26

如果您想要break单独的循环,那么您可以在循环中使用break

将过多的或单个break放入循环中,只会使break循环知道它在其中。

代码语言:javascript
复制
#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;
}
票数 0
EN

Stack Overflow用户

发布于 2022-09-24 04:58:16

为了打破嵌套循环,您可以使用goto语句。

代码语言:javascript
复制
#include <iostream>

using namespace std;

int main()
{
    for (int i = 0; i < 20; i++)
    {
        while (true) 
        { 
            while (true) 
            { 
                goto break_outer_loop;
            } 
        }
    }

break_outer_loop:
    
    cout << "END";

    return 0;
}

注意,通常应该避免使用goto。但是,为了突破嵌套循环,it is generally considered acceptable

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73576943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档