我们被分配了使用动态编程在 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
}