2013-04-04 56 views
-1

我有2d数组,表示矩阵,我需要通过重载< <运算符打印它。打印矩阵与重载<<运算符

是重载运算符的声明是

std::ostream &operator <<(std::ostream &os, const Matrix &matrix) { 

return os; 
} 

和它工作得很好 - 当我写

ostringstream os; 
Matrix a; 
// fill in the matrix 
os << a; 

调用此函数...但虽然我读过一些教程,我没有发现,如何使它打印出值...有人可以告诉我soma示例代码,如何实现打印矩阵中的值的一些非常基本的操作?

BTW-的矩阵可以有任意尺寸..

+2

这取决于类'Matrix',你没有显示... – 2013-04-04 21:30:54

+0

请看看注释bellow @Paul R的答案 – Dworza 2013-04-04 21:42:04

回答

0

没有看到你的Matrix类的定义很难猜出它是如何实现的,但你可能想是这样的:

std::ostream& operator<< (std::ostream &os, const Matrix &matrix) { 
    for (int i = 0; i < matrix.rows; ++i) 
    { 
     for (int j = 0; j < matrix.cols; ++j) 
      os << " " << matrix.data[i * matrix.cols + j]; 
     os << std::endl; 
    } 
    return os; 
} 

要显示矩阵,你会再只是这样做:

Matrix a; 
// fill in the matrix 
cout << a; 

这将调用上述operator<<执行打印的矩阵stdou吨。显然你可以使用任何其他适当的输出流而不是cout

+0

nope ...我知道,如何从矩阵中获取值以及如何通过forloops进行迭代...... IE代码:'std :: ostream&operator << (std :: ostream&os,const Matrix&matrix){ cout <<“printing”<< endl; os <<“qwerty”; return os;它打印输出到控制台,但“qwerty”根本不打印: -/ – Dworza 2013-04-04 21:41:19

+0

好的 - 我想你只需要使用'cout'而不是创建一个'ostringstream' - 参见上面的编辑。 – 2013-04-04 21:43:47

+0

我想用'cout',但是我不能...我真的必须使用我在这里发布的模板... – Dworza 2013-04-04 21:46:04

1

你要么需要编写从结果ostringstreamcout

ostringstream os; 
Matrix a; 
// fill in the matrix 
os << a; 
cout << os.str(); 

,或者你直接做:

Matrix a; 
// fill in the matrix 
cout << a; 
+0

正如我所说的那样 - 我不能......我发现了一些使用sprintf的解决方案,可以工作,但我无法使其工作。char buf [40]; \t的snprintf(BUF,BUF的sizeof, \t \t “%04d-%02d-%02D 02D%:%02D:%02D”, \t \t Y,M,d,H,分钟,秒); \t os << buf;' – Dworza 2013-04-04 21:57:17

+2

@Dworza对不起,你的问题和意见根本没有意义。 – 2013-04-04 22:11:35