C++11的for循环的新用法
字符串
string str = "this is a string";
for(auto ch : str)
cout << ch << endl;
等价于
for(int i = 0; i < str.size(); i++)
cout << str[i] << endl;
vector
vector<int> v = {1, 2, 3, 4, 5};
for(auto i : v)
cout << i << endl;
等价于
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
二维vector
vector<vector<int>> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for(auto i : v)
for(auto j : i)
cout << j << endl;
等价于
for(int i = 0; i < v.size(); i++)
for(int j = 0; j < v[i].size(); j++)
cout << v[i][j] << endl;
数组
int ary[] = {1, 2, 3, 4, 5};
for(auto i : ary)
cout << i << endl;
等价于
for(int i = 0; i < 5; i++)
cout << ary[i] << endl;
map
map<char, int> m = {{'a', 1}, {'b', 2}, {'c', 3}};
for(auto t : m)
cout << t.first << ' ' << t.second << endl;
等价于
for(map<char, int> :: iterator itr = m.begin(); itr != m.end(); itr++)
cout << itr ->first << ' ' << itr ->second << endl;
本文详细介绍了C++11中引入的新型for循环语法,通过实例展示了其在字符串、一维和二维vector、数组以及map等数据结构上的应用,与传统for循环进行了对比,帮助读者快速掌握并应用这一特性。
4941

被折叠的 条评论
为什么被折叠?



