Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Last active November 18, 2020 22:02
Show Gist options
  • Save Alwinfy/67ae7f0b197d92a7687dfa99038d7465 to your computer and use it in GitHub Desktop.
Save Alwinfy/67ae7f0b197d92a7687dfa99038d7465 to your computer and use it in GitHub Desktop.
cursed multi-dim array code
#include <cstdio>
/*
template<class T>
T prod(T l) {
return l;
}
template<class T, class ...Args>
T prod(T l, Args &&...args) {
return l * prod(args...);
}*/
template<class T>
struct array_alloc {
using type = T *;
static T *make(int size) {
return new T[size];
}
static void free(T *&arr) {
delete[] arr;
arr = nullptr;
}
};
template<class T>
struct array_alloc<T *> {
using type = T **;
template<class ...Args>
static T **make(int l, int w, Args &&...args) {
T **refs = new T *[l];
refs[0] = array_alloc<T>::make(l * w, args...);
for(int i=1; i<l; i++)
refs[i] = refs[i - 1] + w;
return refs;
}
static void free(T **&arr) {
array_alloc<T>::free(*arr);
delete[] arr;
arr = nullptr;
}
};
template<class T, size_t s>
struct multi_array: multi_array<T *, s - 1> {};
template<class T>
struct multi_array<T, 1>: array_alloc<T> {};
int main() {
auto data = multi_array<int, 4>::make(2, 3, 4, 5);
for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
for(int k=0; k<4; k++)
for(int l=0; l<5; l++)
data[i][j][k][l] = (i << 12) + (j << 8) + (k << 4) + l;
for(int i=0; i<2; i++)
for(int j=0; j<3; j++) {
for(int k=0; k<4; k++)
for(int l=0; l<5; l++)
printf("%04x ", data[i][j][k][l]);
puts("");
}
multi_array<int, 4>::free(data);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment