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 verify if I can 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.
More info about performance impact of t() and operator():
I read that some libraries both use t() in O(1) and O(rows*cols), according to what is going to be used the matrix for. But doing t() in O(1) seems to be a good first step. If then I call a method I know it would access row by row, then I could do the copy transpose at that moment.
And for taking the if: the idea is to put all the weight of the operation in t() and to have the fastest operator(), because t() would be call once in a while and operator() a lot. I also want to know how to do this because it might become helpful in another situation.
The question
Maybe i lack enough English to make this clear: the objective of the question is to find a good way to change the behavior of operator(). Not to improve Matrix() (advice is much appreciated though), nor to discard any way of changing the behavior of operator() just because it might not be better than the if. Ultimately, I will analyze, code and post the one that has the best performance between what i have and what i get as answers. But to know what has better performance i need those codes/algorithms/patterns/whatever, and I think this may help other people in different but similar situations.