C++11 for循环 C++11的for循环的新用法(推荐)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++11 for循环 C++11的for循环的新用法(推荐)

lMonster81   2021-11-10 我要评论
想了解C++11的for循环的新用法(推荐)的相关内容吗,lMonster81在本文为您仔细讲解C++11 for循环的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C++11,for循环,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;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们