在学习了python之后,一直觉得python的语法很方便,特别是python中遍历数组的方式,无需配置特别的参数就可以完全遍历,C语言是很难实现的,不过我发现C++中有对应的函数可以实现。
1、常规的for循环
C++中正常的for循环算法如下所示:
for ( init; condition; increment )
{
statement(s);
}
其中init用于初始化参数;condition用于条件判断,在满足条件时继续执行for循环;increment用于在每一轮循环改变变量的值。
应用实例如下:
#include <iostream>
using namespace std;
int main()
{
for (int a = 0; a <5; a = a + 1)
{
cout << "a 的值为:" << a << endl;
}
system("pause");
return 0;
}
执行结果为:
a 的值为:0
a 的值为:1
a 的值为:2
a 的值为:3
a 的值为:4
请按任意键继续. . .
2、基于范围的for循环
基于范围的for循环可以遍历整个数组:
for ( type *ele: array)
{
statement(ele);
}
其中type是遍历的数组的类型,ele代指某元素,array指的是整个遍历的数组。
应用实例如下:
#include <iostream>
using namespace std;
int main()
{
int a[10] = {2,1,3,4,5,6,1,2,3,5};
for (int &x : a)
{
cout << x << ' ';
}
cout << '\n';
// auto 可以用于直接获取变量
for (auto &x : a) {
cout << x << ' ';
}
cout << '\n';
system("pause");
return 0;
}
应用结果为:
2 1 3 4 5 6 1 2 3 5
2 1 3 4 5 6 1 2 3 5
请按任意键继续. . .