我想实现一个矩阵模板类使用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