for ( : ) 是 C++ 的 范围 for 循环(range-based for loop),它在 C++11 引入,用于简化对容器、数组等数据结构的遍历。
for (declaration : range_expression) {
// 循环体
}
declaration:
const 修饰符等。auto x:拷贝当前元素。效率低auto& x:引用当前元素,可修改原数据。效率高const auto& x:引用当前元素,但不可修改。效率高range_expression:
std::vector)、数组或其他支持范围遍历的数据结构。for 循环的执行流程range_expression 的第一个元素开始。declaration。range_expression 的最后一个元素后结束。范围 for 循环适用于以下场景:
std::vector、std::list、std::set 等。std::array。{1, 2, 3, 4}。begin() 和 end() 方法。begin() 和 end() 函数。代码示例:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// 使用值遍历(拷贝元素)
cout << "Value iteration:" << endl;
for (auto x : v) {
cout << x << " ";
}
cout << endl;
// 使用引用遍历(直接操作元素)
cout << "Reference iteration:" << endl;
for (auto& x : v) {
x *= 2; // 修改元素
}
// 使用 const 引用遍历(只读操作)
cout << "Const reference iteration:" << endl;
for (const auto& x : v) {
cout << x << " "; // 输出修改后的值
}
cout << endl;
return 0;
}
运行结果:
Value iteration: 1 2 3 4 5 Reference iteration: Const reference iteration: 2 4 6 8 10
2.遍历普通数组
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
// 值遍历
cout << "Value iteration:" << endl;
for (auto x : arr) {
cout << x << " ";
}
cout << endl;
// 引用遍历
cout << "Reference iteration:" << endl;
for (auto& x : arr) {
x += 5; // 修改数组元素
}
// 检查数组内容
cout << "Modified array:" << endl;
for (auto x : arr) {
cout << x << " ";
}
cout << endl;
return 0;
}
运行结果:
Value iteration: 10 20 30 40 50 Reference iteration: Modified array: 15 25 35 45 55
3、遍历用户自定义类型:
#include <iostream>
#include <vector>
using namespace std;
struct CustomRange {
vector<int> data;
auto begin() { return data.begin(); }
auto end() { return data.end(); }
};
int main() {
CustomRange cr = {{1, 2, 3, 4, 5}};
for (auto x : cr) {
cout << x << " ";
}
return 0;
}
运行结果:
1 2 3 4 5
范围 for 循环提供了一种简洁、直观的方式来遍历容器和数组,优点如下:
根据具体场景选择合适的循环变量形式(值、引用、常量引用)以实现性能和功能的平衡。