2.for循环

新版的for循环集简洁性与实用性与一身。先看几个例子

1.string 

string str = "hello";
//以前的用法
 for(int i = 0; i < str.size(); i++)
    {
            cout<< str[i]<<endl;
        }
//等价于
    for(char ch:str)
{
        cout<<ch<<endl;
}
//一般这样写
for(auto ch: str)
{
cout<<ch<<endl;
}

2.vector

vector<int> ivec{1,4,2,6,8};

vector<int>iterator::it;
for(it=ivec.begin();it!=ivec.end();it++)
{
    cout<<*it<<endl;
}

//等价于

for(auto it:ivec)
{
    cout<<it<<endl;
}

3.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;
发布了24 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/yonggandess/article/details/103024658