C++11新特性之四：range-based for loops

``````int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < 10; i++)
cout << arr[i];  ``````

``````std::vector<int> vec {1,2,3,4,5,6,7,8,9,10};
for (std::vector<int>::iterator itr = vec.begin(); itr != vec.end(); itr++)
cout << *itr;  ``````

``````int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto n : arr)
cout << n;

std::vector<int> vec {1,2,3,4,5,6,7,8,9,10};
for (auto n :vec)
std::cout << n;  ``````

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

int main()
{
std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "修改前" << endl;
for (auto &n : vec)
std::cout << n++;
cout << endl;

cout << "修改后" << endl;
for (auto j : vec)
std::cout << j;
cout << endl;

system("pause");
return 0;
}``````

1.注意auto自动推导的类型

``````std::map<string, int>  map = { { "a", 1 }, { "b", 2 }, { "c", 3 } };
for (auto &val : map)
cout << val.first << "->" << val.second << endl;  ``````

2.注意容器本身的约束

``````set<int> ss = { 1, 2, 3, 4, 5, 6 };
for (auto& n : ss)
cout << n++ << endl;  ``````

3.当冒号后不是容器而是一个函数

``````#include <iostream>
#include <set>
using namespace std;

set<int> ss = { 1, 2, 3, 4, 5, 6 };
const set<int> getSet()
{
cout << "GetSet" << endl;
return ss;
}

int main()
{
for (auto n : getSet())
cout << n << endl;

system("pause");
return 0;
}``````

4.不要在for循环中修改容器

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

vector<int> vec = { 1, 2, 3, 4, 5, 6 };

int main()
{
for (auto n : vec)
{
cout << n << endl;
vec.push_back(7);
}

system("pause");
return 0;
}``````