在c++中,我们可以定义三维数组,并且可以将之作为参数直接传递。
定义:
#include <iostream>
#include <windows.h>
using namespace std;
const int x = ;
const int y = ;
const int z = ;
int main() {
double foo[x][y][z];
for (int i = ; i < x; i++) {
for (int j = ; j < y; j++) {
for (int k = ; k < z; k++) {
foo[i][j][k] = 1.0;
}
}
}
cout << foo[][][] << endl; // 1.0
system("pause");
return ;
}
如上所示,我们设置的是静态数组,所以必须在定义三维数组之前确定其大小,为了程序的可维护性,建议使用const int进行定义。
将三维数组作为参数传递:
#include <iostream>
#include <windows.h>
using namespace std;
const int x = ;
const int y = ;
const int z = ;
int bar(double arr[][y][z]);
int main() {
double foo[x][y][z];
for (int i = ; i < x; i++) {
for (int j = ; j < y; j++) {
for (int k = ; k < z; k++) {
foo[i][j][k] = 1.0;
}
}
}
cout << foo[][][] << endl; // 1.0
bar(foo);
system("pause");
return ;
}
int bar(double arr[][y][z]) {
cout << "function invoked value: " << arr[][][] << endl;
return ;
}
如上所示,最终结果为:
function invoked value1
注意,在传递三维数组作为参数时,数组的第一个[]中为空,而第二第三个不能为空。
这样,对于大部分情况下的三维数组就可以轻松处理了。