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循環的新用法的文章就介紹到這瞭,更多相關C++11 for循環內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: