Created
March 24, 2020 18:16
-
-
Save sekrasoft/56f6f71476ec66bf865f98ff3c9e9278 to your computer and use it in GitHub Desktop.
Multidimentional array wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cassert> | |
template <typename T, size_t dim> | |
class NDArray: protected NDArray<T, dim - 1> { | |
public: | |
template <typename T1, typename... D> | |
NDArray (T1* data, size_t size, D...sizes): NDArray<T, dim - 1>(data, sizes...), size(size) {} | |
NDArray<T, dim - 1> operator [] (size_t i) { | |
assert(i >= 0 && i < size); | |
NDArray<T, dim> that = *this; | |
that.data += that.parent_elements() * i; | |
return static_cast<NDArray<T, dim-1>>(that); | |
} | |
protected: | |
size_t parent_elements() { return NDArray<T, dim - 1>::nelements(); } | |
size_t nelements() { return size * NDArray<T, dim - 1>::nelements(); } | |
size_t size; | |
}; | |
template <typename T> | |
class NDArray<T, 1> { | |
public: | |
NDArray(T* data, size_t size): data(data), size(size) {} | |
T& operator [] (size_t i) { | |
assert(i >= 0 && i < size); | |
return data[i]; | |
} | |
protected: | |
size_t nelements() { return size; } | |
T* data; | |
size_t size; | |
}; | |
int main() { | |
int x[2*3*5*7]; | |
for (int i=0; i<sizeof(x)/sizeof(int);i++) x[i] = i+1; | |
NDArray<int, 4> arr(x, 2, 3, 5, 7); | |
for(int i=0, n=0; i<2; i++) | |
for(int j=0; j<3; j++) | |
for(int k=0; k<5; k++) | |
for(int l=0; l<7; l++, n++) | |
std::cout << arr[i][j][k][l] << (arr[i][j][k][l] == x[n] ? "" : "ERROR") << " "; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment