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;
}
运行结果: