C++ 的几个for 循环,范围for语句
嵌入式Linux
共 531字,需浏览 2分钟
· 2020-11-25
我认为做嵌入式开发也需要学习C++开发,可能我们学习的不只是一种编程语言,而是一种编程思想,C++相对于C语言来说,会需要更多的想象力,原因就是C++的特点太多了。
不过,我们可以通过学习C++的知识,来掌握面向对象的编程思想,有了这样的思想后,再去看代码或者去做自己的项目,是非常有帮助的。
这个号是我的僚机号,会发一些大号发不了、或者没有档期发的内容,欢迎大家关注。
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 + + 请按任意键继续. . .
评论
C++核心准则ES.72:如果存在明显的循环变量,for语句要好于while语句
ES.72: Prefer a for-statement to a while-statement when there is an obvious loop variableES.72:如果存在明显的循环变量,for语句要好于while语句Reason(原因)Readability: the complete logic of the loop i...
面向对象思考
0
C++核心准则ES.73:如果没有明显的循环变量,while语句要好于for语句
ES.73: Prefer a while-statement to a for-statement when there is no obvious loop variableES.73:如果没有明显的循环变量,while语句要好于for语句Reason(原因)Readability.可读性Example(示例)int events =...
面向对象思考
0