我想實現一個矩陣模板類使用std :: vector。與std :: vector的奇怪行爲
代碼:
// matrix.h
template <class T>
class matrix
{
public:
~matrix(void);
matrix(int rows, int cols):_rows(rows),_cols(cols){ _size = _rows*_cols;init();} //
private:
matrix(void);
void init(); // sets up _matirx
//DATA
size_t _rows;
size_t _cols;
std::vector<T> _matrix;
}
// continued in matrix.tpp file
template <class T>
void matrix<T>::init(){
_matrix = std::vector<T>(_rows*_cols);
for(size_t i = 1; i <= _rows ;i++){
for(size_t j = 1 ; j <= _cols ; j++){
_matrix[(i - 1)*_rows + (j - 1)] = 0 ;
}
}
}
template <class T>
matrix<T>::matrix(const matrix<T>& rhs)
{
_matrix = rhs._matrix;
_rows = rhs._rows;
_cols = rhs._cols;
}
//in Source.cpp
matrix<int> ABC = matrix<int>(4,2) ;
// Gives Debug Assertion Failed , subscript error in VS
matrix<int> ABC = matrix<int>(4000,4000) ;// Works , No Error
matrix<int> ABC = matrix<int>(2,4) ; // Works No Error
我知道如何使用的push_back,我會重新使用它實現類,但我想知道,爲什麼它在過去兩年的情況下,在第一種情況下不呢?我的直覺是,在第一種情況下,一些元素沒有被初始化。 std :: vector中是否存在對索引i的限制,在i + 2元素初始化之前,i + 1個元素是否必須初始化? 還是有更微妙的事情呢?
- 謝謝
你不需要明確地設置每個元素爲0,'std :: vector'會爲你做到這一點。 – dreamlax 2015-04-04 22:17:51
@dreamlax,但如果我沒有將第i個元素設置爲零並使用vec [i],是不是會給我一個編譯錯誤?有沒有辦法設置vec的最大尺寸?這樣我可以無憂無慮地編制索引? - 感謝 – nnrales 2015-04-04 22:22:50
不要使用基於1的for循環,它們令人困惑和反慣例。 – 2015-04-04 22:23:10