一、引言
C++11中新增的for循环功能,通常被称为范围基于的for循环(Range-based for loop),它是一种简化的for循环语法,用于遍历容器(如数组、std::vector、std::list等)或其他序列中的所有元素。这种循环使得代码更加简洁、易读,并且减少了编写迭代代码时出错的机会。
二、基本语法
for (datatype var: collection){
// 循环代码
}
语法说明:
datatype:表示某一数据类型,常使用auto自动推断。也可以使用类型的引用;
var:变量名
collection:可以迭代的集合类型,如数组,及STL中的大部分容器(stack和queue不可以)。
三、示例
1. 遍历数组
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
for (auto elem : arr) {
std::cout << elem << ' ';
}
//输出1 2 3 4 5
return 0;
}
2. 遍历vector
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2