C++11包含一種新的 for 循環,稱爲基於範圍的 for 循環,可以簡化對數組元素的遍歷。格式如下:
for(Type VarName : Array){
//每個元素的值會依次賦給 VarName
}
Type參數可以使用auto類型,這樣遍歷更舒坦
比如:
int array[] = {2, 4, 6, 8};
for(int &x : array){
x++;
}
for(auto x : array){
cout << x;
}
cout << endl;
輸出爲3579
這種基於範圍的遍歷還有一個方法可以引用
在c11標準下可以執行的特殊格式的for循環語句,區別在於引用類型可以改變原來的值
比如 #include<iostream> using namespace std; int main() { string s("hello world"); for(auto c:s) c='t'; cout<