Vector of Vectors to create matrix(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.
这篇关于Vector of Vectors 创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vector of Vectors 创建矩阵
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
