【发布时间】:2018-02-22 17:11:26
【问题描述】:
我有一个std::vector<T> 类型的多项式和一个std::vector<std::vector<T>> 类型的矩阵,它们都有类。每个类的输出(在我的情况下为 void print()-function)工作正常。现在我创建了一个由多个多项式组成的矩阵like this,但我并不完全确定如何为其创建输出。
假设我有一个多项式 p1:Polynomial<T> p1{0,1,2}。我的多项式::print 函数正确解释并返回:x^2+x+1。
对于Matrix<T> m1(2,2,0) 类型的“普通”矩阵,一个用 0 填充的 2x2 矩阵,它可以通过 Matrix::print() 正确返回,并且:
0, 0
0, 0
现在,假设我想要一个多项式矩阵 m1:Matrix<Polynomial<T>> mp(2,2,p1),一个 2x2 矩阵填充的多项式 p1。代码被接受,但现在我想使用 matrix::print() 打印矩阵,所以我得到:
x^2+x+1, x^2+x+1
x^2+x+1, x^2+x+1
最小的工作示例:
#include<iostream>
#include<vector>
using namespace std;
template <typename T>
class Polynomial;
template <typename T>
class Matrix
{
public:
Matrix(std::vector<std::vector<T> > ma);
Matrix(int rows, int cols, T const & init);
Matrix(const Matrix & m);
~Matrix();
Matrix ();
void print();
friend void Polynomial<T>::print();
private:
std::vector<std::vector<T>> Ma;
};
template <typename T>
Matrix<T>::Matrix(std::vector<std::vector<T>> ma)
:Ma(ma)
{}
template <typename T>
Matrix<T>::Matrix(int rows, int cols, T const & init)
{
std::vector<std::vector<T>> b(rows, std::vector<T>(cols, init));
Ma=b;
}
template <typename T>
Matrix<T>::~Matrix()
{}
template <typename T>
Matrix<T>::Matrix() :
Matrix(1,1,0)
{}
template <typename T>
Matrix<T>::Matrix(const Matrix & m)
{
Ma = m.Ma;
}
template <typename T>
void Matrix<T>::print()
{
for (auto i = 0; i < Ma.size(); i++)
{
for (auto j = 0; j < Ma[i].size(); j++)
if ( j == Ma.size()-1 )
{
cout << Ma[i][j]; //This causes problems
}
else
cout << Ma[i][j] << ", \t";
cout << endl;
}
}
template <typename T>
class Polynomial
{
public:
Polynomial(std::vector<T> const& coef);
Polynomial(std::initializer_list<T> const& coef);
void print();
const int getdeg();
const T getKoeff(int index) const;
friend class Matrix<T>;
Polynomial ();
friend void print();
private:
std::vector<T> coefficient;
};
template <typename T>
Polynomial<T>::Polynomial(std::vector<T> const& coef) :
coefficient(coef)
{}
template <typename T>
Polynomial<T>::Polynomial(std::initializer_list<T> const& coef) :
coefficient(coef)
{}
template <typename T>
Polynomial<T>::Polynomial ()
{
coefficient = new std::vector<T> [coefficient.getdeg()];
coefficient[0]=0;
}
template <typename T>
void Polynomial<T>::print() //Reduced version for demonstration purposes, but
{
for ( int i = getdeg(); i >= 0; i-- )
{
cout << coefficient[i] << "x^" << i; //the output is always of the type cout << xyz
}
}
template <typename T>
const int Polynomial<T>::getdeg()
{
int g = coefficient.size()-1;
return g;
}
int main()
{
typedef double T;
Polynomial<T> p1{0,1,2};
p1.print();
Matrix<Polynomial<T>> mp(2, 3, Polynomial<T>{0});
// mp.print(); //When this is commented out chaos ensues
return 0;
}
2x^21x^10 被返回(注意:+&- 从符号中排除,因为代码太长了)。
matrix::print() 可能由于cout 在处理多项式结果时出现问题而导致问题。
有人知道如何使 matrix::print() 为多项式矩阵提供有用的结果吗?提前谢谢你。
【问题讨论】: