C++中遍历数组

C++中数组不像Java中的有length属性,所以不能直接进行遍历,怎么办呢?

首先,来看C++中一个有用的操作符sizeof。sizeof操作符的作用是返回一个对象或类型名的长度,返回值得类型为size_t,长度的单位是字节。

来看一个实例:

#include <iostream>

using namespace std;

int main()
{
	size_t length;
	length = sizeof(char);
	cout<<"The length of char is "<<length<<endl;
	length = sizeof(short);
	cout<<"The length of short is "<<length<<endl;
	length = sizeof(int);
	cout<<"The length of int is "<<length<<endl;
	length = sizeof(long);
	cout<<"The length of long is "<<length<<endl;
	
	return 0;

}

运行结果为:



那么怎么遍历一个数组呢?请看下面实例:

#include <iostream>

using namespace std;

int main()
{
	int arr[] = {1,2,3,4,5,6};
	for (int i = 0; i < sizeof(arr)/sizeof(int); i++)
	{
		cout<<arr[i]<<" ";
	}
	cout<<endl;
	
	return 0;

}

运行结果:


  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值