0

I was trying to to implement a quick Matrix class ( Complete with Eigen values and fast exponention and inverses). As you might guess this consisted a lot of operator overloading , am now trying to overload the [] such that for

matrix A(3,3);
A[i][j]  // A[i][j] returns the matrix element at ith row and jth collumn in matrix

This is what i have so far

class matrix
{
public:
int row,col;
vector< vector<long long int> > a;

matrix(int x,int y)
{
    row = x;
    col = y;
    a.resize(x);
    for(int i=0;i<x;i++)
        a[i].resize(y);
}

vector<long long int>& operator[](int i)
{
    return a[i];
}

matrix operator*(const matrix &M)
{
    matrix __A(row,M.col);

    for(int i=0;i<row;i++)
        for(int j=0;j<row;j++)
            for(int k=0;k<M.col;k++)
                __A.a[i][j] += (M.a[k][j] * a[i][k]);

    return __A;
}
};

However Here the A[i] returns a vector<long long int> and then further i do A[i][j] it should give long long int . It kinda works all right , but i not satisfied , how do i make A[i][j] return a "%lld" directly ? i tried

 long long int& operator[][](int i, int j)
 { return a[i][j]; }

But of'course,it didn't worked for me. How do overload the operator to get the value directly? (Also any tip for improving current class is welcome :) )

Abhishek Gupta
  • 1,297
  • 13
  • 28
  • 2
    There is no operator `[][]` in C++. Best variant is to use `operator[]`, that returns vector, and then use `operator[]` on it. You also can overload operator `()` for work with 2 params. – ForEveR Dec 30 '14 at 14:47
  • ...or some own "MatrixRow" or something instead of the vector. But a class to return is necessary in every case. – deviantfan Dec 30 '14 at 14:49
  • @deviantfan sorry, but i don't get what you mean by "MatrixRow" , would you please give an example? – Abhishek Gupta Dec 30 '14 at 14:51
  • @bolov yeah, it is similar to that , too bad it doesn't pop up when you search for `operator [][] overload` in google , However i have already did that, was just wandering if there is a more direct /efficient way for this – Abhishek Gupta Dec 30 '14 at 14:59
  • since there is no `[][]` operator in C++ you can only use a proxy. Or you can use a function like get(int, int) – bolov Dec 30 '14 at 15:02

0 Answers0