lundi 2 novembre 2015

N-dimensional tensor based on std::vector

I want to define n-dimensional data structure using std::vector. I have a problem with definition of operator(). Lets have a look at a sample 2D structure

class my_data {

public:
  my_data (size_t N, size_t M) : tab(N*M), _N(N), _M(M) {}

  const double& operator() (size_t i, size_t j) const {
     return tab.at(i * M + j);
  }

  double& operator() (size_t i, size_t j) {
     return tab.at(i * M + j);
  }

private:
   std::vector<double> tab;
   size_t _N;
   size_t _M;

};

I would like to define such a structures for any dimension using templates , but I don't know if it is possible. So basically what I would like to have is something like that

my_data<4> vec (1,2,3,4);

defines 4D 'tensor' with sizes 1,2,3,4 (number of all elements 1*2*3*4). You can now access and change values by typing

vec (0,0,0,0) = 2.0;

Aucun commentaire:

Enregistrer un commentaire