是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
当前回答
Break将只退出包含它的最内层循环。
你可以使用goto来跳出任意数量的循环。
当然,goto通常被认为是有害的。
使用break函数[…]是否合适?
使用break和goto会使判断程序的正确性变得更加困难。请看这里关于这个问题的讨论:Dijkstra不是疯子。
其他回答
只是使用lambdas添加一个显式的答案:
for (int i = 0; i < n1; ++i) {
[&] {
for (int j = 0; j < n2; ++j) {
for (int k = 0; k < n3; ++k) {
return; // yay we're breaking out of 2 loops here
}
}
}();
}
当然,这种模式有一定的局限性,显然只适用于c++ 11,但我认为它非常有用。
虽然这个答案已经提出了,但我认为一个很好的方法是这样做:
for(unsigned int z = 0; z < z_max; z++)
{
bool gotoMainLoop = false;
for(unsigned int y = 0; y < y_max && !gotoMainLoop; y++)
{
for(unsigned int x = 0; x < x_max && !gotoMainLoop; x++)
{
//do your stuff
if(condition)
gotoMainLoop = true;
}
}
}
你可以用try…catch。
try {
for(int i=0; i<10; ++i) {
for(int j=0; j<10; ++j) {
if(i*j == 42)
throw 0; // this is something like "break 2"
}
}
}
catch(int e) {} // just do nothing
// just continue with other code
如果必须同时跳出几个循环,通常会出现异常。
我不确定这样做是否值得,但你可以用一些简单的宏来模拟Java的命名循环:
#define LOOP_NAME(name) \
if ([[maybe_unused]] constexpr bool _namedloop_InvalidBreakOrContinue = false) \
{ \
[[maybe_unused]] CAT(_namedloop_break_,name): break; \
[[maybe_unused]] CAT(_namedloop_continue_,name): continue; \
} \
else
#define BREAK(name) goto CAT(_namedloop_break_,name)
#define CONTINUE(name) goto CAT(_namedloop_continue_,name)
#define CAT(x,y) CAT_(x,y)
#define CAT_(x,y) x##y
使用示例:
#include <iostream>
int main()
{
// Prints:
// 0 0
// 0 1
// 0 2
// 1 0
// 1 1
for (int i = 0; i < 3; i++) LOOP_NAME(foo)
{
for (int j = 0; j < 3; j++)
{
std::cout << i << ' ' << j << '\n';
if (i == 1 && j == 1)
BREAK(foo);
}
}
}
另一个例子:
#include <iostream>
int main()
{
// Prints:
// 0
// 1
// 0
// 1
// 0
// 1
int count = 3;
do LOOP_NAME(foo)
{
for (int j = 0; j < 3; j++)
{
std::cout << ' ' << j << '\n';
if (j == 1)
CONTINUE(foo);
}
}
while(count-- > 1);
}
c++不支持命名循环,就像Java和其他语言一样。您可以使用goto,或创建您使用的标志值。在每个循环结束时检查标志值。如果它被设置为true,那么您可以跳出该迭代。