2012-11-25 26 views
1

我有一個Matrix類和我重疊的基本操作奇怪的數據時,矢量

template<class T> 
Matrix<T>::Matrix(unsigned rows, unsigned cols) : 
     rows_(rows), cols_(cols) { 
    index = 0; 
    data_.reserve(rows * cols); 
} 
template<class T> 
Matrix<T> Matrix<T>::operator=(const Matrix<T>& m) { 

    rows_ = m.rows(); 
    cols_ = m.cols(); 
    index = 0; 

    data_ = m.data_; 
    return *this; 
} 

但是,當我使用等於運算符我越來越奇怪值:

Matrix<double> a(5, 5); 
Matrix<double> b(2, 2); 
a << 5, 2, 4, 5, 6, 1, 3, 1, 2, 5, 2, 5, 2, 7, 2, 9, 2, 1, 0.1, 0.43, 1, 0, 0, 0, 1; 
a.print("a"); 
b = a; 
b.print("B"); 

輸出:

a 
5 2 4 5 6 
1 3 1 2 5 
2 5 2 7 2 
9 2 1 0.1 0.43  
1 0 0 0 1 
B 
0 0 0 0 0 
2.42092e-322 4.94066e-324 4.94066e-324 0 3.26083e-322  
0 6.66322e-319 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

這是爲什麼?

回答

1

它看起來好像你的意思是使用resize()而非reserve():前者實際上改變了std::vector<double>的大小,而後者只是安排足夠的空間存在,但它並沒有把內部的任何對象,也沒有複製內容。

+0

我正在C++中重寫c代碼,我是否必須釋放該向量的內存?例如,如果我使用新的或malloc然後釋放內存我必須使用刪除或免費 –

+0

'std :: vector '將負責釋放它分配給它的成員的內存。一般來說,你只需要鏡像你的分配,而在C++中,你最好永遠不要調用'malloc()':而是使用'new T()'。它將確保調用該對象的構造函數。 –