1

I am coding a matrix calculator and I wanted it to calculate operations like: 2*A, A*3 (where A is a matrix). So, I wrote this:

matrix operator* (double x , matrix mat)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

matrix operator* (matrix mat, double x)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

(matrix is the name of class, n is the size (matrixes are square), t is a static, 2-dimensional array t[n][n])

As you can see I coded 2 completely identical functions, where the only difference is the order of arguments. Is there any way to merge them into one? Other than converting x to diagonal matrix and multiplying them as 2 matrices.

(btw it's my first post on this forum, so please, don't be too harsh to me for asking such trivial question)

sfotiadis
  • 959
  • 10
  • 24
MartinYakuza
  • 60
  • 1
  • 12
  • And pass the `mat` parameter as `const matrix &mat` to avoid making copies. – 1201ProgramAlarm Mar 21 '20 at 21:33
  • @1201ProgramAlarm see https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading, it can be more efficient to take first argument by value in binary operators – Alan Birtles Mar 21 '20 at 21:36
  • @AlanBirtles It can be, but not here with the way the functions are written since all the data is copied out of the parameter. They'd need to be rewritten to take advantage of that. – 1201ProgramAlarm Mar 21 '20 at 21:39
  • @1201ProgramAlarm yes, good point, I forgot about that. – MartinYakuza Mar 21 '20 at 21:47

1 Answers1

1

Just make one function call the other:

matrix operator* (double x , matrix mat)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

matrix operator* (matrix mat, double x)
{
    return x * mat;
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60