Question

I have a class with the following constructor

//matrix constructor
mat::mat(int nrows,int ncols){
  this->nrows=nrows;
  this->ncols=ncols;
  this->dat=new float *[nrows];
  for(int i=0;i<nrows;i++){
    this->dat[i]=new float[ncols];
     for(int j=0;j<ncols;j++){
        this->dat[i][j]=-9999;
      }
   }
}

as you see the constructor is for a matrix which contains floats. I would like to sometimes use the same constructor to create a matrix of integers. How can i do this with minimal change to the above code? i don't want to create a new class for the matrices to contain integers.

Thanks

Was it helpful?

Solution

You can write a templated mat class:

template<typename T>
class mat {
    //matrix constructor
    mat(int nrows,int ncols) {
        this->nrows=nrows;
        this->ncols=ncols;
        this->dat=new T *[nrows];
                   // ^ 
        for(int i=0;i<nrows;i++){
        this->dat[i]=new T[ncols];
                      // ^ 
        for(int j=0;j<ncols;j++){
            this->dat[i][j]=-9999;
      }
   }
};

Replace every occurrence of float with T, and put all the code inlined in your mat.h header file.

UPDATE:

how would the above code look with std::vector?

template<typename T>
class mat {
    //matrix constructor
    mat(int nrows_,int ncols_)
    : nrows(nrows_) , ncols(ncols_) {
        dat.resize(nrows);
        for(int i=0;i<nrows;i++) {
            dat[i].resize(ncols);
            for(int j=0;j<ncols;j++) {
                dat[i][j]=-9999;
            }
        }
    }
private:
    int nrows;
    int ncols;
    std::vector<std::vector<T>> dat;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top