如何在c++中跳出嵌套循环
How do you break out of nested loops in C++?
我是c++的初学者,我想知道如何跳出嵌套循环。是否有break(2)
#include <iostream>
using namespace std;
int main() {
for (int x = 5; x < 10; x++) {
for (int j = 6; j < 9; j++) {
for (int b = 7; b < 12; b++) {
// Some statements
// Is break(2) right or wrong
// or can I use 'break; break;'?
}
}
}
}
您可以使用goto
。本质上是相同的函数
#include <iostream>
using namespace std;
int main() {
for(int x = 5; x < 10; x++) {
for(int j = 6; j < 9; j++) {
for(int b = 7; b < 12; b++) {
if (condition)
goto endOfLoop;
}
}
}
endOfLoop:
// Do stuff here
}
不,不幸的是没有break(2)
(或者可能是幸运的,取决于你对作用域深度嵌套的看法)。
有两种主要方法来解决这个问题:
- 在
break
之前设置一个标志,告诉外部循环停止。 - 将一些嵌套循环放入函数中,以便它们可以执行
break
,也可以执行return
跳出。例如:
// returns true if should be called again, false if not
bool foo() {
for(int j = 6; j < 9; j++) {
for(int b = 7; b < 12; b++) {
if (something) {
break; // one level
}
if (whatever) {
return true; // two levels
}
if (another) {
return false; // three levels
}
}
}
}
int main() {
for(int x = 5; x < 10; x++) {
if (!foo()) {
break;
}
}
}
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 毕达哥拉斯三重嵌套循环误解
- T(n) 表示嵌套循环
- 2 个嵌套循环的时间复杂度
- 嵌套循环背后的逻辑
- 使用 %s C++嵌套循环
- 嵌套循环和重复迭代器
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- C++在乘法图中放置随机值(嵌套循环)
- 如何使用 OpenMP 减少嵌套循环?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 学习嵌套循环C++与示例混淆
- 如何在CUDA中嵌套循环
- std::vector上的嵌套循环
- 具有动态数组分配的OpenMP嵌套循环
- 两个嵌套循环的运行时间复杂性:二次型还是线性