Vector of Vectors 创建矩阵

Vector of Vectors to create matrix(Vector of Vectors 创建矩阵)

本文介绍了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 创建矩阵

基础教程推荐