//数组初始化
int arr[10]{0,1,2,3,4,5,6,7,8,9};//默认初始化为10个0
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
//数组不允许拷贝和赋值
//int arr1[10] = arr;//错误 不允许直接赋值和用数组初始化
int *arrP[10]{ 0 };//定义存放指针的数组
//int &arrRe[10]{};//错误 不存在存放引用的数组
int (*parr)[10] = &arr;//定义一个指向数组的指针
int (&rearr)[10](arr);//引用一个数组
for (int i = 0; i < 10; i++)
{
cout << (*parr)[i] << endl;
}
for (int i = 0; i < 10; i++)
{
cout << rearr[i] << endl;
}
cout << "=====默认初始化====================" <<endl;
//定义在函数体外部数组会默认初始化,函数体内部不会。string类型在内部还是外部都会被初始化为空
string sa[10];
int ia[10];
for (int i = 0; i < 10; i++)
{
cout << ia[i] << endl;
}
for (int i = 0; i < 10; i++)
{
cout << sa[i] << endl;
}
cout << "=====数组的下标类型====================" <<endl;
//size_t:数组的下标类型
constexpr size_t arr_size = 10;
int iarr[arr_size];
for (size_t ix = 0; ix < arr_size; ++ix)
{
iarr[ix] = ix;
}
for (size_t ix = 0; ix < arr_size; ++ix)
{
cout << iarr[ix] <<endl;
}
cout << "=====指针和数组====================" << endl;
//指针和数组
string str[]{"aaa","bbb","ccc","ddd"};
string *pst1(&str[0]);
string *pst2(str);
auto pstr3(&str[0]);//pstr3为 string *
//指针作为数组的迭代器,
double dbarry[10]{1.123465,2,3,4,5,6,7,8,9,0};
double *p(dbarry);
while (p && *p)
{
cout << *p << endl;
++p;
}
cout << "=====begin和end的使用====================" << endl;
//begin和end的使用
double *beg(begin(dbarry));
double *last(end(dbarry));
while (beg != last && *beg)
{
cout << *beg << endl;
++beg;
}
cout << "=====下标与指针====================" << endl;
//下标与指针
int *ap2 = &arr[2];//指向下标为2 的元素
int num1 = ap2[-1];//等价于*(ap2-1);
cout <<num1 <<endl;
cout << "=====多维数组====================" << endl;
//多维数组:c++没有多维数组,有的是数组的数组
int iarrs[2][3]{ {1,2,3},{3,4,5} };
int (&reArrs)[3] = iarrs[1];//引用第二个[3]数组
int (*pArrs)[3] = iarrs;//指向含有3个整数的数组
pArrs = &iarrs[1];//指向第二个[3]数组
for (int i = 0; i < 3; i++)
{
cout << (*pArrs)[i] << endl;
}
//使用auto 和使用begin和end都能达到效果
for (auto p = iarrs; p < iarrs + 2; p++)
{
for (auto q = *p; q < *p + 3; q++)
{
cout << *q << endl;
}
}
cout << "=====数组的类型别名====================" << endl;
//数组的类型别名
using int_array = int[3];
typedef int int_array[3];
for (int_array *p = iarrs; p < iarrs + 2; p++)
{
for (int *q = *p; q < *p + 3; q++)
{
cout << *q << endl;
}
}