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;

 

原文链接: https://www.cnblogs.com/lMonster81/p/10433840.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++11的for循环的新用法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/285807

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午8:51
下一篇 2023年2月15日 上午8:53

相关推荐