基于范围的for循环
语法:
for ( for-range-declaration : expression ) statement
注意一般用auto表达类型。不需要修改时常用引用类型
例子:
1 // range-based-for.cpp 2 // compile by using: cl /EHsc /nologo /W4 3 #include <iostream> 4 #include <vector> 5 using namespace std; 6 7 int main() 8 { 9 // Basic 10-element integer array. 10 int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 11 12 // Range-based for loop to iterate through the array. 13 for( int y : x ) { // Access by value using a copy declared as a specific type. 14 // Not preferred. 15 cout << y << " "; 16 } 17 cout << endl; 18 19 // The auto keyword causes type inference to be used. Preferred. 20 21 for( auto y : x ) { // Copy of 'x', almost always undesirable 22 cout << y << " "; 23 } 24 cout << endl; 25 26 for( auto &y : x ) { // Type inference by reference. 27 // Observes and/or modifies in-place. Preferred when modify is needed. 28 cout << y << " "; 29 } 30 cout << endl; 31 32 for( const auto &y : x ) { // Type inference by reference. 33 // Observes in-place. Preferred when no modify is needed. 34 cout << y << " "; 35 } 36 cout << endl; 37 cout << "end of integer array test" << endl; 38 cout << endl; 39 40 // Create a vector object that contains 10 elements. 41 vector<double> v; 42 for (int i = 0; i < 10; ++i) { 43 v.push_back(i + 0.14159); 44 } 45 46 // Range-based for loop to iterate through the vector, observing in-place. 47 for( const auto &j : v ) { 48 cout << j << " "; 49 } 50 cout << endl; 51 cout << "end of vector test" << endl; 52 }