范围for

1、范围for是C++11的新特性,语法如下:

for(declaration:expression)
	statement;
  • 范围for迭代的范围是确定的,在使用的过程中无需担心下标越界的情况。
  • 可以遍历定义了begin()end() 方法,且返回该方法返回迭代器的类对象。如STL中的 vector,set,list,map,queue,deque,string 等对象。
  • 不能用于指针如使用new生成的数组将不能使用范围for
  • 由于数组在遍历的时候会转换成指针,所以在遍历多维数组的时候,除最内层循环外,其他所有循环的控制变量都要使用引用的形式。

2、一维数组中的应用

int arr1[] = { 10,20,3,4,5,6,8,9 };
// 此时可以正常遍历
for (auto &i : arr1)
	cout << i << " ";
cout << endl;


int *arr2 = new int[10];
// 错误:因为arr2的类型是 int* ,试图在 int* 内遍历是不合法的。
for (auto &j : arr2)
{
	cout << j << " ";
}

3、在多维数组中的应用

int arr[2][3] = { {1,2,3},{4,5,6} };

// 正确:其中最内层的循环控制变量 col 可以不用引用类型。
for (auto &row : arr)
	for (auto &col : row)
		cout << col << " ";

将上面的外层循的环控制变量 row 声明成引用类型,是为了避免数组被自动转换成指针。若不使用引用类型,则循环将变成如下所示:

// 错误:此时外层循环控制变量不是引用类型
for (auto row : arr)
	for (auto col : row)
		cout << col << " ";

这种程序将无法通过编译。因为第一个循环遍历arr的所有元素,这些元素实际上是一个个大小为3的数组。而row变量不是引用类型,所以编译器初始化row变量时,会自动的将这些数组形式的元素转换成指向该数组内首元素的指针。这样得到的row类型就是 int * ,这时内层循环就不合法了。

4、在string、vector等容器中的应用

string str("this is just a test !");
for (auto i : str)
{
	cout << i << " ";
}
发布了213 篇原创文章 · 获赞 48 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/Jeffxu_lib/article/details/104767689