我们平常定义二维数组的时候,常用方法就类似于这样:

int a[10][10];

但是,我们可以采用array来实现二维数组。这个在定义的时候就看上去没那么直观了。

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<array>
using namespace std;

const size_t rows = 2;
const size_t columns = 3;
void printArray(const array<array<int, columns>, rows>&);


int main()
{
	array<array<int, columns>, rows> array1 = { 1,2,3,4,5,6 };
	array<array<int, columns>, rows> array2 = { 1,2,3,4,5 };
	cout << "Values in array1 by row are:\n";
	printArray(array1);
	cout << "\nValues in array2 by row are:\n";
	printArray(array2);
}


void printArray(const array<array<int, columns>, rows>& a)
{
	for (auto const& row : a)
	{
		for (auto const& element : row)
			printf_s("%d ", element);
		cout << endl;
	}
}

定义的方法就是在一个array里面,把它的类型设置为另一个array

然后在迭代的时候就先迭代每一个行,再迭代每一个列。就其实就是一个通过嵌套一维数组的方式实现多维数组。

三维的定义就看起来就也是类似的,在二维数组的前提下,再往里面嵌套一层一维数组就可以了。

比如,把上面的代码改一改,就得到了下面的三维数组的代码

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<array>
using namespace std;

const size_t rows = 2;
const size_t columns = 3;
const size_t heights = 4;
void printArray(const array<array<int, columns>, rows>&);
void print_threeDimensionArray(const array<array<array<int, columns>,rows>, heights>&);



int main()
{
	array<array<int, columns>, rows> array1 = { 1,2,3,4,5,6 };
	array<array<int, columns>, rows> array2 = { 1,2,3,4,5 };
	array<array<array<int, columns>, rows>, heights> array3 = { 1,2,3,4,5,6,7,8,9,10,11,12 };
	cout << "Values in array1 by row are:\n";
	printArray(array1);
	cout << "\nValues in array2 by row are:\n";
	printArray(array2);

	cout << "\nValues in array3 are:\n";
	print_threeDimensionArray(array3);
	
}


void printArray(const array<array<int, columns>, rows>& a)
{
	for (auto const& row : a)
	{
		for (auto const& element : row)
			printf_s("%d ", element);
		cout << endl;
	}
}

void print_threeDimensionArray(const array<array<array<int, columns>, rows>, heights>& a)
{
	int js=0;
	for (auto const& height : a)
	{
		js++;
		printf_s("\n正在输出第%d层:\n", js);
		for (auto const& row : height)
		{
			for (auto const& element : row)
					printf_s("%d ",element);
			cout << endl;
		}
			

	}
}

执行结果:

Values in array1 by row are:
1 2 3
4 5 6

Values in array2 by row are:
1 2 3
4 5 0

Values in array3 are:

正在输出第1层:
1 2 3
4 5 6

正在输出第2层:
7 8 9
10 11 12

正在输出第3层:
0 0 0
0 0 0

正在输出第4层:
0 0 0
0 0 0

对比分析可以发现,数组的第一个维度要写在最外面,第二个维度写在中间,最高维度的元素尺寸写在最里面。这个有点难理解,但是它确实是这样的[doge]

你也可能喜欢

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注