前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++中遍历数组

C++中遍历数组

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-25 15:46:13
2.3K0
发布2019-01-25 15:46:13
举报

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

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

来看一个实例:

代码语言:javascript
复制
#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;

}

运行结果为:

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

代码语言:javascript
复制
#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;

}

运行结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014年03月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档