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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM