2013-04-04 54 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