c ++参数与ref问题的兼容性

时间:2015-09-21 12:06:18

标签: c++ vector

我目前正在使用模板编写c ++矩阵。 我有一个矢量构造函数,它获取行数,列数和 一个长向量,它是(num-of-cols * num-of-rows)长。

这是当前的构造函数代码:

Matrix<T>(unsigned int rows, unsigned int cols, const vector<T>&cells)
{
    this->rowsNum = rows;
    this->colsNum = cols;

    int j = 0;
    for(int i = 0; i < rowsNum; i++)
    {
        for(int k = 0; k < colsNum; k++)
        {
            this->mat[i][k] = cells[j];
            j++;
        }
    }

}

这是我从main调用函数:

int main()
{
    const vector<int> v {1, 2, 3, 4, 5};
    Matrix<int> m {1, 5, v};
    cout << m << endl;

}

每次运行它时,程序都会在构造函数的中间粉碎, 在行:

this->mat[i][k] = cells[j];

调试器还向我展示了c ++页面&#34; stl_vector.h&#34;,在这些行中:

  reference
  operator[](size_type __n) _GLIBCXX_NOEXCEPT
  { return *(this->_M_impl._M_start + __n); }

我不知道该怎么做。我相信它的const和ref兼容性,但是 我不知道什么是错的。

1 个答案:

答案 0 :(得分:1)

您需要resize变量mat(如果它是vector)或new到正确的rowcols大小。如果尚未分配该内存,则无法在mat中分配这些索引。