우리는 동적 곱셈을 사용하여 행렬 곱셈을위한 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 메소드를 편집했습니다. 나는 이제 내가 알아낼 수있는 또 다른 문제가있다. 행렬을 인쇄 할 때, 단지 0이 인쇄됩니다. 마치 계산이 이루어지는 것처럼 보이지 않습니다. 어떤 아이디어? 또한, minmult가 호출되기 전에 INF에 대한 모든 행렬 위치를 인스턴스화합니다. – Busch
@SeanHellebusch : 변수가 무엇을 의미하는지 문서화해야합니다. 그들이 무엇인지 알아내는 데는 시간이 걸렸습니다. 그렇다면'INF'의 가치는 무엇입니까? 어떻게 초기화합니까? 여러분의 행렬이 0으로 초기화되면,'ops