0
点赞
收藏
分享

微信扫一扫

C++多维数组的理解与元素遍历

南柯Taylor 2022-01-10 阅读 51
#include<iostream>
#include<typeinfo>

using arr1d = int[4];//一维数组的类型别名

int main()
{
	//多维数组初始化
	int a0[2][2] = { 1,2,3,4}; // int[2][2]类型
	int a[2][6] = { { 1,2,3,4,5,6 },{ 7,8,9,10,11,12 } }; // int[2][6]类型
	int b[2][3] = {};// int b[2][3] = {0, 0, 0, 0, 0, 0};
	int c[2][3] = { { 1,2,3 } ,{ 4} };// int c[2][3] = {{1, 2, 3}, {4, 0, 0}};
	int d[2][4] = { { 1,2,3 } ,{ 4} };// int d[2][4] = { {1, 2, 3, 0}, {4, 0, 0, 0} };
	int e[2][3][4];//缺省初始化
	int f[][3] = { 1,2,3,4 };//int f[2][3] = {{1, 2, 3}, {4, 0, 0}};
	arr1d g[2] = { 1,2,3,4,5,6,7,8 };//使用类型别名初始化数组  arr1d g[2] = {{1, 2, 3, 4}, {5, 6, 7, 8}};

	//多维数组的本质
	std::cout  << "数组本质: \n";// {1, 2, 3, 4, 0, 0}
	std::cout << &f[0][0] << " " << &f[0][1] << " " << &f[0][2] << "\n";
	std::cout << &f[1][0] << " " << &f[1][1] << " " << &f[1][2] << "\n";


	//多维数组隐式转换为指针,只有高维进行转换,其他维度信息会被保留
	auto e_ptr = e;
	auto e1_ptr = *e_ptr;

	std::cout << "多维数组隐式转换为指针: \n";
	std::cout << typeid(e).name() << std::endl;// int[2][3][4]
	std::cout << typeid(e_ptr).name() << std::endl;// int(*__ptr64)[3][4]
	std::cout << typeid(e1_ptr).name() << std::endl;// int(*__ptr64)[4]
	
		
	//多维数组元素遍历
	std::cout << "多维数组元素(索引)遍历1:" << std::endl;
	size_t index0 = 0;
	while (index0 < 2)
	{
		size_t index1 = 0;
		while (index1 < 6)
		{
			std::cout << a[index0][index1]<<" ";
			index1 += 1;
		}
		std::cout << std::endl;
		//std::cout << "index0:" << index0<<std::endl;
		index0 += 1;
	}
	
	
	std::cout << "多维数组元素(指针)遍历2:" << std::endl;
	auto ptr0 = std::cbegin(a);//ptr0 类型:int const (*ptr0)[6] 常量数组指针
	while (ptr0 != std::cend(a))
	{
		auto ptr1 = std::cbegin(*ptr0);//ptr1 类型:const int * ptr1 常量指针
		while (ptr1 != std::cend(*ptr0))
		{
			std::cout << *ptr1 << " ";
			ptr1 += 1;
		}
		std::cout << std::endl;
		ptr0 += 1;
	}
	std::cout << "\n";
	
	
	std::cout << "多维数组元素遍历3(引用range based for):" << std::endl;
	//可使用 https://cppinsights.io/ 理解range based for的实现流程
	for (auto &x : a) //int a[2][6] --> int (&x)[6]
	{
		for (auto s : x)//int (&x)[6] --> int s
		{
			std::cout << s << " ";
		}
		std::cout << "\n";
	}
	
}

结果:

数组本质:
0000006384F9FA08 0000006384F9FA0C 0000006384F9FA10
0000006384F9FA14 0000006384F9FA18 0000006384F9FA1C
多维数组隐式转换为指针:
int [2][3][4]
int (* __ptr64)[3][4]
int (* __ptr64)[4]
多维数组元素(索引)遍历11 2 3 4 5 6
7 8 9 10 11 12
多维数组元素(指针)遍历21 2 3 4 5 6
7 8 9 10 11 12

多维数组元素遍历3(引用range based for)1 2 3 4 5 6
7 8 9 10 11 12
举报

相关推荐

0 条评论