QNANO
Tensor2.h
1 #ifndef QNANO_NEW_TENSOR2_DEFINED_H
2 #define QNANO_NEW_TENSOR2_DEFINED_H
3 
4 #include <complex>
5 #include <iostream>
6 #include <cstdlib>
7 #include "tools/Reader.h"
8 
10 template <typename T> class template_Tensor2{
11 public:
12  //sizes:
13  size_t size[2];
14  //data block:
15  T *data;
16 
17  inline size_t get_index(size_t i, size_t j)const{
18  return i*size[1]+j;
19  }
20 
21 public:
22  inline size_t get_totalsize()const{ return size[0]*size[1]; }
23 
24 protected:
25 
26  void allocate(){ data=new T[get_totalsize()]; }
27  void deallocate(){ delete[] data; }
28 public:
29  inline size_t get_size(size_t i)const{return size[i];}
30  void resize(size_t i, size_t j){
31  size[0]=i; size[1]=j;
32  deallocate();
33  allocate();
34  }
35  void set_zero(){
36  size_t ts=get_totalsize();
37  for(size_t i=0; i<ts; i++)data[i]=0.;
38  }
39 
40  const T &operator()(size_t i, size_t j)const{
41  return data[get_index(i,j)];
42  }
43  T &operator()(size_t i, size_t j){
44  return data[get_index(i,j)];
45  }
46  const T &get_check(int i, int j){
47  if(i<0 || i>=(int)size[0] || j<0 || j>=(int)size[1] ){
48  std::cerr<<"Tensor2: out of bounds!"<<std::endl;
49  exit(1);
50  }
51  return data[get_index(i,j)];
52  }
53 
54  void swap_lines(size_t l1, size_t l2){
55  for(size_t k=0; k<size[1]; k++){
56  T tmp=data[get_index(l1,k)];
57  data[get_index(l1,k)]=data[get_index(l2,k)];
58  data[get_index(l2,k)]=tmp;
59  }
60  }
61 
62 
63  //Constructors and copy operators
64  void copy(const template_Tensor2 &other){
65  resize(other.get_size(0),other.get_size(1));
66  for(size_t i=0; i<get_totalsize(); i++){
67  data[i]=other.data[i];
68  }
69  }
70  template_Tensor2 &operator=(const template_Tensor2 &other){
71  copy(other);
72  return *this;
73  }
74  template_Tensor2(const template_Tensor2 &other){
75  copy(other);
76  }
78  size[0]=size[1]=0;
79  allocate();
80  }
81  template_Tensor2(size_t i, size_t j){
82  size[0]=i; size[1]=j;
83  allocate();
84  set_zero();
85  }
87  deallocate();
88  }
89 
90 
91 };
92 
93 
96 
97 #endif
98 
99 
100 
Class to store a rank-2 (complex) tensor, i.e., a matrix:
Definition: Tensor2.h:10