我們被賦予了使用動態編程在C++中編程用於矩陣乘法的任務。他告訴我們使用遞歸併給了我們一個自定義的書面矩陣類。我寫了下面的遞歸算法,但我得到一個錯誤,當我跑,說遞歸矩陣乘法算法未能計算
Object& Matrix<Object>::at(uint, uint) [with Object = unsigned int, uint = unsigned int]: Assertions 'row < rows && col < cols' failed.
任何想法,爲什麼發生這種情況?我在下面列出了他的矩陣類和遞歸矩陣乘法。
#ifndef MATRIX_H
#define MATRIX_H
#include <cassert>
typedef unsigned int uint;
template <class Object>
class Matrix
{
public:
Matrix(uint rows, uint cols);
Object & at(uint row, uint col);
const Object & at(uint row, uint col) const;
~Matrix();
Matrix(const Matrix<Object> & m); // Copy constructor
Matrix & operator= (const Matrix<Object> & m); // Assignment operator
uint numrows() const;
uint numcols() const;
private:
uint rows;
uint cols;
Object* data;
};
template <class Object>
Matrix<Object>::Matrix(uint rows, uint cols)
: rows(rows), cols(cols)
{
assert(rows > 0 && cols > 0);
data = new Object[ rows * cols ];
}
template <class Object>
Matrix<Object>::~Matrix()
{
delete[] data;
}
template <class Object>
Object & Matrix<Object>::at(uint row, uint col)
{
assert(row < rows && col < cols);
return data[ cols * row + col ];
}
template <class Object>
const Object & Matrix<Object>::at(uint row, uint col) const
{
assert(row < rows && col < cols);
return data[ cols * row + col ];
}
template <class Object>
uint Matrix<Object>::numrows() const
{
return rows;
}
template <class Object>
uint Matrix<Object>::numcols() const
{
return cols;
}
int minmult(Matrix<uint> & P,
Matrix<uint> & M,
const vector<uint> & d,
uint i,
uint j)
{
if(M.at(i,j) != INF)
{
return M.at(i,j); //already has been defined
}
else if(i == j)
{
M.at(i,j) = 0; //base case
}
else
{
//M.at(i,j) = UINT_MAX; //initialize to infinity
for(uint k = i; k <= j-1; k++)
{
uint ops = minmult(P, M, d, i, k)
+ minmult(P, M, d, k+1, j)
+ d.at(i-1)*d.at(k)*d.at(j);
if(ops < M.at(i,j))
{
M.at(i,j) = ops;
P.at(i,j) = k;
}
}
}
return M.at(i,j); //returns the final cost
}
感謝您的建議,我已經在問題中編輯了我的minmult方法。我現在有另一個問題,我似乎可以弄清楚。當我打印矩陣時,只打印零點。它似乎並沒有進行任何計算。有任何想法嗎?另外,在minmult被調用之前,我將所有矩陣位置實例化爲INF。 – Busch 2013-03-05 04:36:26
@SeanHellebusch:你應該記錄你的變量的含義。我花了一段時間才弄清楚它們是什麼。那麼,INF的價值是什麼?你如何初始化它?如果你的矩陣初始化爲0,那麼'ops
2013-03-05 14:21:22