Vector of Vectors 创建矩阵
我正在尝试输入二维矩阵的维度.然后使用用户输入来填充这个矩阵.我尝试这样做的方法是通过向量(向量的向量).但是每当我尝试读取数据并将其附加到矩阵时,我都会遇到一些错误.
I am trying to take in an input for the dimensions of a 2D matrix. And then use user input to fill in this matrix. The way I tried doing this is via vectors (vectors of vectors). But I have encountered some errors whenever I try to read in data and append it to the matrix.
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
for(int j = 0; j<CC; j++)
{
cout<<"Enter the number for Matrix 1";
cin>>matrix[i][j];
}
}
每当我尝试这样做时,它都会给我一个下标超出范围的错误.有什么建议吗?
Whenever I try to do this, it gives me a subscript out of range error. Any advice?
推荐答案
事实上,向量的两个维度都是 0.
As it is, both dimensions of your vector are 0.
相反,将向量初始化为:
Instead, initialize the vector as this:
vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
matrix[i].resize(CC);
这将为您提供一个维度矩阵 RR * CC
,其中所有元素都设置为 0
.
This will give you a matrix of dimensions RR * CC
with all elements set to 0
.
相关文章