I got here trying to transpose a matrix in O(1). So right now I have something like this:
#include <vector>
template <class T>
class Matrix { //intended for math matrix
public:
Matrix(int Rows, int Cols){matrix = vector<vector<T> >(Rows, vector<T>(Cols,0)); transpose = false; cols = Cols; rows = Rows;}
Matrix(const Matrix<T> &M){matrix = M.matrix; transpose = M.transpose; cols = M.cols; rows = M.rows;}
~Matrix(){}
void t(){
transpose = !transpose;
swap(cols,rows);
}
T& operator()(int row, int col){
if(transpose)
return matrix[col][row];
else
return matrix[row][col];
}
private:
vector<vector<T> > matrix;
bool transpose;
int cols;
int rows;
};
In that code I have what I want: t() is O(1) and operator() is also O(1). But operator() is used a lot and I want to take away the if
.
So, to improve performance I want to have something like this:
#include <vector>
template <class T>
class Matrix { //intended for math matrix
public:
Matrix(int Rows, int Cols){matrix = vector<vector<T> >(Rows, vector<T>(Cols,0)); transpose = false; cols = Cols; rows = Rows;}
Matrix(const Matrix<T> &M){matrix = M.matrix; transpose = M.transpose; cols = M.cols; rows = M.rows;}
~Matrix(){}
T& originalShape(int row, int col){return matrix[row][col];}
T& transposedMatrix(int row, int col){return matrix[col][row];}
void t(){
transpose = !transpose;
swap(cols,rows);
if(transpose)
&operator() = &transposedMatrix;
else
&operator() = &originalShape;
}
T& operator()(int row, int col){return matrix[row][col];}
private:
vector<vector<T> > matrix;
bool transpose;
int cols;
int rows;
};
Of course, that doesn't work. And I didn't find anything useful for this case.
Is there anything I can do to improve this?
Aucun commentaire:
Enregistrer un commentaire