2015-04-04 36 views
1

我想實現一個矩陣模板類使用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個元素是否必須初始化? 還是有更微妙的事情呢?

  • 謝謝
+1

你不需要明確地設置每個元素爲0,'std :: vector'會爲你做到這一點。 – dreamlax 2015-04-04 22:17:51

+0

@dreamlax,但如果我沒有將第i個元素設置爲零並使用vec [i],是不是會給我一個編譯錯誤?有沒有辦法設置vec的最大尺寸?這樣我可以無憂無慮地編制索引? - 感謝 – nnrales 2015-04-04 22:22:50

+0

不要使用基於1的for循環,它們令人困惑和反慣例。 – 2015-04-04 22:23:10

回答

1

在這裏,你可能有超出越界訪問:

  • 與4×2尺寸:

    _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 ; 
        } 
    } 
    

    最後的循環執行過程中把你的例子:i-1 = 3,_rows = 4和j-1 = 1,因此您正在訪問大小爲8的向量的第13個元素。

  • 與4000x4000大小,您訪問超過16000000(4000-1)* 4000 +(4000-1)= 15999999 th元素,因此沒有出界限制訪問。

最後一個例子也是如此。

+0

是的,它回答了我的問題,謝謝 – nnrales 2015-04-04 22:44:21

2

簡單的錯字。

_matrix[(i - 1)*_rows + (j - 1)] = 0 ; 

應該

_matrix[(i - 1)*_cols + (j - 1)] = 0; 

通過工作在紙上的循環的每次迭代會發現這一點。

+0

是的,它的工作原理。我應該更加小心。 – nnrales 2015-04-04 22:37:42

+0

你能解釋爲什麼最後兩種情況可以工作,即使這個錯誤存在? – nnrales 2015-04-04 22:41:17

+0

Hiura給了我答案,當我有足夠的代表點時,我會對這個答案滿意。感謝您的答覆。 – nnrales 2015-04-04 22:45:45