0
点赞
收藏
分享

微信扫一扫

C++基于范围的for循环

您好 2022-03-19 阅读 65
c++

文章目录


前言

提示:当处理array对象的所有元素时,如果没有访问array对象元素下标的需求,那么最好使用基于范围的for语句。

基于范围的for循环语句,允许程序员不使用计数器就能完成所有元素的遍历。


一、基于范围的for循环语句

1.基于范围的for语句的语法形式:

for(范围变量声明:表达式)
	语句

其中范围变量声明含有一个类型名称和一个标识符(例如int item),表达式是需要迭代遍历的array对象。范围变量声明中的类型必须与array对象的元素类型相一致,而标识符代表循环的连续迭代中下一个array对象元素的值。基于范围的 for语句可以和大多数C++标准库中预制的数据结构(通常称为容器)一起使用,包括类array和vector。

2.示例

#include<iostream>
#include<bits/stdc++.h> 
using namespace std;
int main(){
	array < int , 5> items = {1,2,3,4,5}; 
	for(int item : items){
		cout<<item<<"  ";
	}
} 

二、嵌套的基于范围的for语句

1.二维数组基于范围的for循环

为了处理二维array对象的元素,我们采用一个嵌套的循环,其中的外层循环迭代遍历行,而外层循环迭代遍历一个给定行的列。
代码如下(示例):

2.示例

#include<iostream>
#include<bits/stdc++.h> 
using namespace std;

int main(){
	const int row=3, column = 2;
	array< array< int, column > , row> aa;
	for(auto &row : aa){
		for(auto &column : row){
			cin>>column;
		}
	} 
	cout<<endl;
	for(auto &row : aa){
		for(auto &column : row){
			cout<<column<<" ";
		}
	} 
} 
举报

相关推荐

0 条评论