C++特性循环——for ( i : n)
目录
- 写在前面
- 与常规for循环的区别
-
- 常规写法
- C++11写法
- 用法举例
-
- 1.对数组中所有数乘以二
- 2.与auto结合使用
- 3.遍历字符串
- 4.快速求和
- 5.快速求出最大(最小)值
- 6.统计归类
- 7.for_each用法
- 总结
写在前面
当我们在阅读别人写的代码时,有时会出现类似于 for ( i : n) 这样语句,
初学者此时可能会一脸懵逼产生疑惑,因为在我们的老师也许并没有讲这种语法,不过不用担心,接下来通过这篇文章,你一定会熟练掌握这种特殊的for循环用法。
与常规for循环的区别
这种循环是C++11之后才支持的,这种循环方法是基于整体范围的,并不能像常规for循环一样能够任意规定循环范围,但这并不意味着这种方法不如常规for循环,以下是两种方法的对比
常规写法
#includeusing namespace std;int main(){int a[5] = { 0,1,2,3,4 };for (int i = 0; i < 5; i++)cout << a[i] << ' ';return 0;//输出结果为 0 1 2 3 4}
C++11写法
#includeusing namespace std;int main(){int a[5] = { 0,1,2,3,4 };for (int item : a)cout << item << ' ';//item为a数组中的每一项return 0;//输出结果为 0 1 2 3 4}
由此可见两种写法均可以实现对数组的遍历,相比之下,第二种方法更加简洁
用法举例
1.对数组中所有数乘以二
#includeusing namespace std;int main(){int a[5] = { 1,2,3,4,5 };for (int& i : a)//注意一定要用引用i *= 2;//对数组中每个数乘以二for (int i : a)cout << i << ' ';//输出return 0;}
输出结果:
- 要使用引用的原因是基于范围的FOR循环的遍历是只读的遍历,只有将元素声明为引用类型才可以改变元素的值。同样的也可以对数组中每个元素进行其他同样的操作。
2.与auto结合使用
auto同样也是C++11的新特性,可以利用它直接让计算机推导数据类型。
例如:
#includeusing namespace std;int main(){int a[5] = { 1,2,3,4,5 };for (auto item : a)//将int改为autocout << item << ' ';return 0;}
输出结果:
可以看出输出结果同样正确,这是因为计算机自动推导出item的数据类型为int,虽然看起来auto比int需要多写一个字母变得更加麻烦,但是如果对于像pair类型,vector之类的,auto的优势就显而易见了。
3.遍历字符串
#includeusing namespace std;int main(){string s = "abcde";for (auto item : s)cout << item << ' ';return 0;}
输出结果:
4.快速求和
#includeusing namespace std;int main(){int a[5] = { 1,2,3,4,5 };int sum = 0;for (auto item : a)sum += item;cout << sum;return 0;}
输出结果:
5.快速求出最大(最小)值
#includeusing namespace std;int main(){int a[10] = { 10,9,8,7,6,5,4,3,2,1 };int Max = 0;for (auto item : a)if (item > Max)Max = item;cout << Max;return 0;}
输出结果:
6.统计归类
例如求一个数组中正数的个数
#includeusing namespace std;int main(){int a[10] = { -5,-4,-3,-2,-1,1,2,3,4,5 };int ans = 0;for (auto item : a)if (item > 0)ans++;cout << ans;return 0;}
输出结果:
7.for_each用法
for_each 同样是C++11中的新特性,可以对容器进行遍历,需要包含头文件#include"algorithm"
举例:
#include#include#includeusing namespace std;int main(){vector<int>a;for (int i = 0; i < 10; i++)a.push_back(i);for_each(a.begin(), a.end(), [](int i)->void {cout << i << ' '; });return 0;}
输出结果:
总结
关于特性循环的用法还有很多,需要大家去慢慢发掘,熟练掌握着用循环用法不仅能提高我们写代码的效率,同时这用写法也能够能方便他人阅读。