C++ 的几个for 循环,范围for语句

嵌入式Linux

共 531字,需浏览 2分钟

 · 2020-11-25

我认为做嵌入式开发也需要学习C++开发,可能我们学习的不只是一种编程语言,而是一种编程思想,C++相对于C语言来说,会需要更多的想象力,原因就是C++的特点太多了。


不过,我们可以通过学习C++的知识,来掌握面向对象的编程思想,有了这样的思想后,再去看代码或者去做自己的项目,是非常有帮助的。


这个号是我的僚机号,会发一些大号发不了、或者没有档期发的内容,欢迎大家关注。



13939da5608688f2e51413e2e17a785f.webp

C++新标准提供的范围for语句.这种语句遍历给定序列中个元素并对序列中每一个值执行某种操作,其语法形式是:

for(declaration : expression)
   statement

其中,expression部分是一个对象,用于表示一个序列。declaration部分负责定义一个变量,该变量将用于访问序列中的基础元素。每次迭代,declaration部分的变量会被初始化为expression部分的下一个元素值

例子:

#include 

using namespace std;

int main()
{
 string str("this is a c++");
 //每行输出str中的一个字符
 for(auto c : str)
     cout< system("pause");
 return 0;

代码输出:

t
h
i
s

i
s

a

c
+
+
请按任意键继续. . .

代码中的 auto 关键字让编译器来决定 c的类型,每次迭代后,str的下一个字符赋值给 c

看看比较正常的 for 语句

#include 

using namespace std;

int main()
{
 string str("this is a c++");
 for(int i = 0;i  cout< system("pause");
 return 0;

输出:

t
h
i
s

i
s

a

c
+
+
请按任意键继续. . .

第三种方法

#include 

using namespace std;

int main()
{
 string str("this is a c++");
 for(auto i = str.begin(); i!= str.end();++i)
  cout<<(*i)< system("pause");
 return 0;

输出

t
h
i
s

i
s

a

c
+
+
请按任意键继续. . .

第四种方法

使用STL函数,需要包含头文件哦。

#include 
#include 
#include  

using namespace std;

int main()
{
 string str("this is a c++");
 for_each(str.begin(),str.end(),[](char item)
  {
   cout<" ";
  });
 system("pause");
 return 0;

输出

t h i s   i s   a   c + + 请按任意键继续. . .





写代码的篮球球痴微信扫描二维码,关注我的公众号 


浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报