簡體   English   中英

std :: vector的奇怪行為

[英]Strange behavior with 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 + 1元素必須在i + 2元素初始化之前初始化? 還是有更微妙的事情發生?

  • 謝謝

簡單的拼寫錯誤。

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

應該

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

對於循環的每次迭代,在紙上完成它將揭示這一點。

在這里你可能有越界訪問:

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

在最后一個循環執行期間獲取示例:

  • 4x2大小:i-1 = 3,_rows = 4和j-1 = 1,因此您正在訪問大小為8的向量的第13個元素。
  • 對於4000x4000大小,您訪問超過16000000的(4000-1)* 4000 +(4000-1)= 15999999元素,因此沒有越界訪問。

最后一個例子也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM