Created
December 31, 2018 17:30
-
-
Save PanagiotisPtr/b6379e403a25e2fcd5f643c1361d505c to your computer and use it in GitHub Desktop.
Simple n-dimensional array class ( Tensor ) in C++
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
#ifndef TENSOR_H | |
#define TENSOR_H | |
#include <vector> | |
#include <ostream> | |
static bool math_indexing = true; | |
template<typename T, size_t size> | |
class Tensor { | |
public: | |
template<typename ...Args> | |
Tensor(size_t first, Args&&... args){ | |
data = std::vector<Tensor<T, size-1> >(first, Tensor<T, size-1>(args...)); | |
} | |
Tensor<T, size-1> operator[](size_t idx){ return data[idx - math_indexing]; } | |
friend std::ostream& operator<<(std::ostream& out, const Tensor& t){ | |
out << "[ "; | |
for(Tensor<T, size-1> tensor : t.data) | |
out << tensor << ", "; | |
out << "]"; | |
return out; | |
} | |
private: | |
std::vector<Tensor<T, size-1> > data; | |
}; | |
template<typename T> | |
class Tensor<T, 1> { | |
public: | |
Tensor(size_t size) : data(size) {} | |
T operator[](size_t idx){ return data[idx - math_indexing]; } | |
friend std::ostream& operator<<(std::ostream& out, const Tensor<T, 1>& t){ | |
out << "[ "; | |
for(T val : t.data) | |
out << val << ", "; | |
out << "]"; | |
return out; | |
} | |
private: | |
std::vector<T> data; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment