错误:内存位置处的std :: length_error

时间:2018-06-21 08:57:54

标签: c++ vector

当我调用移调函数时,出现以下错误:错误:

std::length_error at memory location

我不确定是什么原因导致错误

//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
}

1 个答案:

答案 0 :(得分:0)

解决方案是将对象作为指针返回或将变量作为引用传递,这是正确的示例:

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;
}

谢谢