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
}