循环结构:重复执行的艺术

发布时间:2026/7/19 13:41:20
循环结构:重复执行的艺术 循环结构重复执行的艺术传统循环与范围 forC 支持 C 的全部循环for、while、do-while。C11 新增范围 forrange-based for简化容器与数组遍历。本篇在 C 循环基础上重点讲解范围 for传统循环详见 C 语言循环结构。一、for 循环与 C 相同#includeiostreamintmain(){for(inti0;i10;i)std::couti ;std::coutstd::endl;return0;}完整 for/while/do-while 语法、break/continue、嵌套循环见 C 第 07 篇。二、范围 forC112.1 基本语法for(declaration:range)statement;遍历数组intarr[]{1,2,3,4,5};for(intx:arr)std::coutx ;遍历 vector#includevectorstd::vectorintvec{10,20,30};for(intv:vec)std::coutv ;2.2 三种遍历方式形式语法说明值拷贝for (auto x : container)修改 x 不影响原容器引用for (auto x : container)可修改元素常引用for (const auto x : container)只读避免拷贝推荐#includeiostream#includevector#includestringintmain(){std::vectorstd::stringnames{Alice,Bob,Charlie};// 只读遍历推荐for(constautoname:names)std::coutname ;std::coutstd::endl;// 修改元素for(autoname:names)name!;for(constautoname:names)std::coutname ;std::coutstd::endl;return0;}2.3 遍历 string#includestringstd::string sHello;for(charc:s)std::coutc;三、while 与 do-while与 C 完全相同intn0;while(n5){std::coutn ;n;}do{std::cout至少执行一次\n;}while(false);四、break 与 continue与 C 相同跳出循环 / 跳过本次迭代。五、实战练习练习1范围 for 求和用std::vectorint存储 1100范围 for 求和。练习2修改元素用for (auto x : vec)将 vector 中所有元素翻倍。练习3嵌套循环打印 5 行 5 列乘法表传统 for 即可。六、总结与延伸本节重点回顾for/while/do-while 与 C 相同范围 forfor (auto x : range)简化遍历大对象用const auto避免拷贝break/continue 用法与 C 相同下节预告下一篇《数组、string 与容器初探》学习 std::string 和 std::vector。延伸阅读C 语言循环结构完整版C 速查 §4.3 范围 for知识点卡片范围 forfor (const auto x : container)修改元素用auto只读用const auto传统 for/while/do-while 与 C 相同下一篇见