for(auto i : v)遍历容器元素

c++11的新特性,v是一个可遍历的容器或流,比如vector类型,i就用来在遍历过程中获得容器里的每一个元素。

for(auto i:v)

for(auto &i:v)

代码1:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto &i : s ) //i是个引用 i到底引用的是什么?
i = toupper(i); //改变成大写,影响s的值
cout<<s<<endl; //s的值是 HELLO
--------------------------------------------------------------
代码2:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto i : s ) //书上说i 是char类型,那s[n]呢?
i = toupper(i); //改变成大写,不影响s的值
cout<<s<<endl; //s的值是 hello

 

c++中for(auto count : counts)

意思是将 counts 容器中的每一个元素从前往后枚举出来,并用 count 来表示,类似于Java中的 for each 语句,举个栗子:

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 int main() {
 5     int a[] = { 1,2,3,5,2,0 };
 6     vector<int>counts(a,a+6);
 7     for (auto count : counts)
 8         cout<< count<< " ";
 9     cout << endl;
10     return 0;
11 }

运行的效果是:

 

这是C++11中的语法,即:Range-based for loop。其中counts应满足:begin(counts), end(counts)是合法的。

因此,它等价于for(some_iterator p = begin(counts); p != end(counts); ++p)且some_type count = *p。

另外还可以是for(auto& count : counts), for(auto&& count: counts)。

它们的区别在于count是值还是引用。

最后,在c++14中还允许for(count : counts),等价于for(auto&& count: counts)。

 

【转载自】

auto关键字:for(auto &i:s)和for(auto i:s) - F~C~H的博客 - CSDN博客 https://blog.csdn.net/qq_34037046/article/details/85221622

c++中for(auto count : counts)是什么意思意思_百度知道 https://zhidao.baidu.com/question/1861076889396870787.html

C++11 之for 新解 auto - Jerry_Jin - 博客园 https://www.cnblogs.com/jins-note/p/9513129.html

浅析C语言auto关键字和C++ 中的auto关键字 - Keep Fighting All The Time - CSDN博客 https://blog.csdn.net/LiuBo_01/article/details/80752734

【C++11新特性】 auto关键字 - 老董 - 博客园 https://www.cnblogs.com/lenmom/p/7988635.html

posted @ 2019-08-29 22:08  ostartech  阅读(32776)  评论(0编辑  收藏  举报