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 @   ostartech  阅读(33597)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2017-08-29 指针存的是什么?
2017-08-29 指针*pbuffer和getchar 读取字符串
点击右上角即可分享
微信分享提示