1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <array>
#include <iostream>
#include <vector>
#define show(variable) std::cout << #variable << " = " << variable << std::endl;
template <typename, std::size_t...> struct NArray;
template <typename T, std::size_t N>
struct NArray<T, N> {using type = std::array<T, N>;};
template <typename T, std::size_t FIRST, std::size_t... REST>
struct NArray<T, FIRST, REST...> {using type = std::array<typename NArray<T, REST...>::type, FIRST>;};
template <typename CONTAINER, typename E, typename T>
void assign (E& element, const CONTAINER&, const T& v) {element = v;}
template <typename CONTAINER, typename SUBARRAY, std::size_t N, typename T>
void assign (std::array<SUBARRAY, N>& narray, const CONTAINER& pos, const T& v) {
assign<CONTAINER> (narray[*pos.begin()], {pos.begin() + 1, pos.end()}, v); // Thanks to JLBorges for this.
}
template <typename T, int... N, typename... ARGS>
typename NArray<T, N...>::type NDimensionalArray (const T& value, ARGS&&... args) {
typename NArray<T, N...>::type narray{};
const auto initializer = {std::forward<ARGS>(args)...};
const int size = sizeof...(N), S = initializer.size() / size;
for (int i = 0; i < S; i++)
assign (narray, std::vector<std::size_t>(initializer.begin() + i*size, initializer.begin() + (i+1)*size), value);
return narray;
}
int main() {
const auto multiArray = NDimensionalArray<double, 5,6,7,8,9> (3.14, 1,2,3,2,4, 3,3,2,1,2, 0,1,3,1,2);
show (multiArray[1][2][3][2][4]); // 3.14
show (multiArray[3][3][2][1][2]); // 3.14
show (multiArray[0][1][3][1][2]); // 3.14
}
|