您可以定义一个别名来定义 std::array 的某个时间,它具有多个维度,几乎与使用 C 样式数组一样简单:
template<typename Type, std::size_t N, std::size_t... Sizes>
struct multi_array {
using type = std::array<typename multi_array<Type, Sizes...>::type, N>;
};
template<typename Type, std::size_t N>
struct multi_array<Type, N> {
using type = std::array<Type, N>;
};
template<typename Type, std::size_t... Sizes>
using multi_array_t = typename multi_array<Type, Sizes...>::type;
然后,由于std::array 可存储在std::vector 中,因此只需使用生成的数组即可:
using my_array = multi_array_t<int, 2, 3>;
my_array arr1 {{
{{1, 2, 3}},
{{4, 5, 6}}
}};
my_array arr2 {{
{{7, 8, 9}},
{{10, 11, 12}}
}};
std::vector<my_array> vector {arr1, arr2};
assert(vector[0][0][1] == 2);
assert(vector[1][1][2] == 12);
Live demo