C++ 中的 break 与 continue
本文将演示关于如何在 C++ 中使用 break
与 continue
语句的多种方法。
使用 break
语句操作符终止循环
与 continue
类似的 break
语句称为跳转语句,用于中断程序执行的流程。在这种情况下,利用 break
来终止 for
循环语句。注意,当到达 break
并执行时,程序离开循环体,从下一条语句- cout << item << "3"
继续。break
必须与迭代或 switch
语句一起使用,并且它只影响最近的循环或 switch
。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::for_each;
int main() {
vector<string> arr1 = {"Gull", "Hawk"};
for (auto &item : arr1) {
cout << item << " 1 " << endl;
for (const auto &item1 : arr1) {
cout << item << " 2 " << endl;
if (item == "Hawk") {
break;
}
}
cout << item << " 3 " << endl;
}
return EXIT_SUCCESS;
}
输出:
Gull 1
Gull 2
Gull 2
Gull 3
Hawk 1
Hawk 2
Hawk 3
使用 continue
语句跳过循环体的一部分
continue
语句是一种语言特征,可用于终止当前的循环迭代并开始执行下一次迭代。continue
只能用于 for
、while
或 do while
循环中。如果语句被放在多个嵌套的循环块中,continue
将只中断内部循环的迭代,并继续评估条件表达式。
在下面的例子中,如果当前的 vector
元素等于 Hawk
,就会达到 continue
语句。执行完毕后,程序就会评估 for
循环表达式,当前 vector
中是否还有其他元素。如果为真,则执行 cout << item << 2
行,否则达到 cout << item << 3
。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::for_each;
int main() {
vector<string> arr1 = {"Gull", "Hawk"};
for (auto &item : arr1) {
cout << item << " 1 " << endl;
for (const auto &item1 : arr1) {
cout << item << " 2 " << endl;
if (item == "Hawk") {
continue;
}
}
cout << item << " 3 " << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
输出:
Gull 1
Gull 2
Gull 2
Gull 3
Hawk 1
Hawk 2
Hawk 2
Hawk 3
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn