for( : )结构的遍历
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 循环提供了一种简洁、直观的方式来遍历容器和数组,优点如下:
- 避免手动处理索引。
- 与 STL 容器配合使用更加自然。
- 减少错误,代码更简洁。
根据具体场景选择合适的循环变量形式(值、引用、常量引用)以实现性能和功能的平衡。
