-1

When I call transpose function I got this error: Error :

std::length_error at memory location

I do not know exactly what could cause the error

//class Matrix.h
class Matrix
{
private:
    std::vector<std::vector<double>> content;
    size_t numberOfRows;
    size_t numberOfColumns;
    double determinant;
};

inline Matrix::Matrix(size_t nRows, size_t nColumns)
    : content(nRows,std::vector<double>(nColumns)),
      numberOfRows(nRows), numberOfColumns(nColumns) {}

const double getValue(size_t i, size_t j) const { 
    return (i >= numberOfRows) || (j >= numberOfColumns) ? NULL : content[i][j]; 
}

void setValue(size_t i, size_t j, double value) {
    (i >= numberOfRows) || (j >= numberOfColumns) ? content[i][j] = NULL : content[i][j] = value;
    determinant = NULL;
}

Matrix Matrix::transpose()
{
    Matrix result(numberOfColumns, numberOfRows);
    for (size_t i = 0; i < numberOfRows; i++)
        for (size_t j = 0; j < numberOfColumns; j++)
            result.setValue(j, i, getValue(i, j));
    return result; /// Error here
}
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
dani2442
  • 41
  • 7
  • (I know that there are better ways to implement this method, but i was trying to 'translate' code from java to c++) – dani2442 Jun 21 '18 at 09:08
  • Related: https://stackoverflow.com/a/4643721/4944425 .Also NULL is used in C for pointers, while you are initializing `double`s, so you should use 0.0 instead (or a completely different logic). – Bob__ Jun 21 '18 at 09:37
  • https://stackoverflow.com/questions/3350385/how-to-return-an-object-in-c – dani2442 Jun 21 '18 at 10:41
  • I totally agree with the [accepted answer](https://stackoverflow.com/a/3350395/4944425) of that question. Have you read it? – Bob__ Jun 21 '18 at 11:04
  • Possible duplicate of [C++ Returning reference to local variable](https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable) – Joseph D. Jun 21 '18 at 14:41

1 Answers1

0

The solution is return the object as a pointer or pass a variable as reference, here is the correct example:

Matrix* Matrix::transpose()
{
    Matrix *result=new Matrix(numberOfColumns, numberOfRows);
    for (size_t i = 0; i < numberOfRows; i++)
        for (size_t j = 0; j < numberOfColumns; j++)
            result.setValue(j, i, getValue(i, j));
    return result;
}

Thank you

dani2442
  • 41
  • 7