C++ 03:范围 for——极简遍历容器的语法糖
·
C++11 引入的范围 for(range-based for),让遍历数组、字符串、容器等序列变得更简洁,告别了传统循环中手动计算长度、管理迭代器的繁琐。
一、核心语法
for (变量 : 序列) {
语句块
}
-
变量:用于接收序列中的每个元素,推荐用
auto自动推导类型。 -
序列:可以是数组、
string、vector等支持迭代器(begin()/end())的对象,也可以是初始化列表。 -
关键规则:
-
只读元素:用
auto x或const auto& x,避免拷贝。 -
修改元素:必须用
auto& x(引用类型),才能直接修改原序列。
-
二、场景 1:遍历数组
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
// 传统for:手动算长度
int len = sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<len; ++i) cout << arr[i] << " ";
cout << endl;
// 范围for:修改元素(必须用引用)
for (auto& x : arr) ++x;
// 范围for:只读遍历
for (auto x : arr) cout << x << " ";
cout << endl;
return 0;
}
//输出
//1 2 3 4 5 6
//2 3 4 5 6 7
三、场景 2:遍历 string
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s = "abcdefghij";
// 范围for:将字符串转大写(修改元素用引用)
for (auto& c : s)
c = toupper(c);
cout << s << endl; // 输出 ABCDEFGHIJ
return 0;
}
四、场景 3:遍历 vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v{1,2,3,4,5,6,7,8};
// 范围for:修改元素
for (auto& x : v) x += 10;
// 范围for:只读遍历
for (auto x : v) cout << x << " ";
cout << endl; // 输出 11 12 13 14 15 16 17 18
return 0;
}
五、核心注意事项
-
修改元素必须用引用:
auto& x才能直接修改原序列,auto x只是拷贝,修改不会生效。 -
只读推荐用 const 引用:
const auto& x既避免拷贝,又保证元素不被意外修改。 -
适用范围广:除了数组、
string、vector,所有提供begin()/end()的标准容器(如list、map等)都可以用范围 for 遍历。
六、总结
范围 for 是 C++11 最实用的语法糖之一,核心优势是简洁、安全、易读:
-
无需手动管理索引或迭代器,减少出错概率。
-
自动适配不同序列类型,代码复用性更强。
-
配合
auto和引用,兼顾性能与可读性。
更多推荐

所有评论(0)