C++11--范围for语句

range-based for statement


C++11新标准引入了一种简单的for循环,这种语句可以遍历容器其他序列所有元素

 从编译器的角度去理解范围for语句的执行过程;实际上就是把范围for语句转换成了传统的for循环语句。 

下面的两种执行过程完全等价,只是采用了不同的标准函数。

//范围for循环
for (decl : coll)
{
       statement
}
//编译器的执行过程1
for (auto _pos = coll.begin(), _end = coll.end(); _pos != _end; ++_pos)
{
       decl = *_pos;
       statement
}
实际使用中的示例代码如下:

下面代码中的vector和数组都采用了C++11的新式初始化方式:Uniform initialization

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	//C++11:Uniform initialization
	vector<int> vec{ 1, 2, 3, 4 };
	int arr[]{ 1, 2, 3, 4 };

	//C++11:range-based for statement
	//pass by value
	for (int i : vec)
		i *= 2;
	for (int i : vec)
		cout<<i<<" ";//1,2,3,4

	//pass by reference,can modify value in vector
	for (int& i : arr)
		i *= 2;	
	for (int i : arr)
		cout << i << " ";//2,4,6,8
}

发布了89 篇原创文章 · 获赞 210 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/i_chaoren/article/details/78825198