你可以使用
std::array
。
如果大小在编译时可知,建议使用
std::array
,这样可以获得连续的内存布局。
#include <iostream>
#include <array>
#include <algorithm>
using Array3D = std::array<std::array<std::array<int, 2>, 2>, 2 >;
Array3D func()
{
Array3D arr3d;
std::array<int, 2> a{ 10, 20 }, b{ 10, 20 }, c{ 10, 20 };
auto input = 1u;
for (std::array<std::array<int, 2>, 2> & array2D : arr3d)
for (std::array<int, 2> & arr : array2D)
std::generate(arr.begin(), arr.end(), [&input] { return input++; });
for (std::array<std::array<int, 2>, 2> & array2D : arr3d)
{
for (std::array<int, 2> & arr : array2D)
{
auto arrIndex = 0u;
for (int& ele : arr)
{
ele = a[arrIndex] * b[arrIndex] * c[arrIndex];
++arrIndex;
std::cout << ele << " ";
}
}
}
return arr3d;
}
另外,您可以使用模板函数(使用大小作为非模板参数),甚至可以通过引用传递array3d
并执行像上面所示的计算!
#include <iostream>
template<std::size_t M, std::size_t N, std::size_t O>
void func(int (&arr3d)[M][N][O])
{
for (std::size_t i = 0; i < M; ++i)
{
for (std::size_t j = 0; j < N; ++j)
{
for (std::size_t k = 0; k < O; ++k)
{
arr3d[i][j][k] = a[k] * b[k] * c[k];
std::cout << arr3d[i][j][k] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
}
}
std::array
? - Some programmer dudestd::array<std::array<std::array<element_type, 2>, 2>, 2>
。 - Peter