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 创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)