首页 > 应用开发 > C/C++ > C++ 循环全解析:从基础到进阶的实用指南
for(初始化表达式; 条件表达式; 更新表达式) {// 循环体}#include <iostream>using namespace std;int main() {int sum = 0;for(int i = 1; i <= 100; i++) {sum += i; // 等价于sum = sum + i}cout << "1-100累加和为:" << sum << endl; // 输出5050return 0;}int i = 1;for(; i <= 100;) { // 省略初始化和更新表达式sum += i;i++;}while(条件表达式) {// 循环体(可能执行0次)}#include <string>using namespace std;bool checkPassword(const string& pwd) {return pwd == "admin123";}int main() {string password;while(!checkPassword(password)) {cout << "请输入密码:";cin >> password;}cout << "登录成功!" << endl;return 0;}do {// 循环体(至少执行1次)} while(条件表达式); // 注意分号结尾int main() {int a, b;char op;do {cout << "请输入表达式(格式:a+b):";cin >> a >> op >> b;switch(op) {case '+': cout << a + b << endl; break;case '-': cout << a - b << endl; break;// 其他运算符处理...}cout << "继续计算?(y/n)";cin >> op;} while(op == 'y' || op == 'Y');return 0;}|
循环类型 |
执行次数 |
条件判断时机 |
|
for |
0+ |
循环前 |
|
while |
0+ |
循环前 |
|
do-while |
1+ |
循环后 |
for(元素类型 变量名 : 容器) {// 遍历操作}int arr[] = {1,2,3,4,5};for(int num : arr) {cout << num << " "; // 输出1 2 3 4 5}#include <map>map<string, int> scores = {{"Alice", 90}, {"Bob", 85}};for(const auto& pair : scores) { // 使用const引用避免拷贝cout << pair.first << ":" << pair.second << endl;}vector<int> nums = {1,2,3};for(int& num : nums) { // 添加&符号num *= 2; // 直接修改容器元素}for(int i=2; i<100; i++) {bool isPrime = true;for(int j=2; j*j<=i; j++) {if(i%j == 0) {isPrime = false;break; // 跳出内层循环}}if(isPrime) cout << i << "是质数" << endl;}vector<int> data = {1,2,0,4,0,6};for(int num : data) {if(num == 0) continue; // 跳过0值元素cout << num << " ";} // 输出1 2 4 6for(int i=0; i<rows; i++) {for(int j=0; j<cols; j++) {if(data[i][j] == target) {goto found; // 跳转到标签位置}}}cout << "未找到目标值" << endl;found:cout << "在(" << i << "," << j << ")位置找到" << endl; // 此处存在变量作用域风险!// 优化前(每次循环都计算)for(int i=0; i<n; i++) {result += data[i] * 3.1415;}// 优化后(常数提前计算)const double pi = 3.1415;for(int i=0; i<n; i++) {result += data[i] * pi;}vector<int> nums = {1,2,3,4,5};for(int i = nums.size()-1; i >= 0; i--) {process(nums[i]); // 更优的内存访问模式}#include <algorithm>vector<int> nums = {1,2,3};for_each(nums.begin(), nums.end(), [](int x){cout << x * 2 << " "; // 输出2 4 6});|
场景类型 |
推荐循环 |
示例场景 |
|
固定次数迭代 |
for 循环 |
数组遍历、数学累加 |
|
条件未知迭代 |
while 循环 |
用户输入验证、文件读取 |
|
至少一次迭代 |
do-while 循环 |
菜单系统、错误重试机制 |
|
容器元素遍历 |
范围 for 循环 |
STL 容器遍历、数组操作 |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046748/viewspace-3087592/ ,如需转载,请注明出处,否则将追究法律责任。