C++ Vector of Vectors 创建矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12375591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vector of Vectors to create matrix
提问by user1487000
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?
每当我尝试这样做时,它都会给我一个下标超出范围的错误。有什么建议吗?
回答by juanchopanza
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
在访问任何元素之前,您必须将向量的向量初始化为适当的大小。你可以这样做:
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR
size CC
vectors, filled with 0
.
这将创建一个RR
大小为向量的CC
向量,填充为0
。
回答by Luchian Grigore
As it is, both dimensions of your vector are 0.
事实上,向量的两个维度都是 0。
Instead, initialize the vector as this:
相反,将向量初始化为:
vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
matrix[i].resize(CC);
This will give you a matrix of dimensions RR * CC
with all elements set to 0
.
这将为您提供一个维度矩阵,RR * CC
其中所有元素都设置为0
。
回答by Shmiddty
I'm not familiar with c++, but a quick look at the documentation suggests that this should work:
我不熟悉 c++,但快速浏览文档表明这应该有效:
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
vector<int> myvector;
for(int j = 0; j<CC; j++)
{
int tempVal = 0;
cout<<"Enter the number for Matrix 1";
cin>>tempVal;
myvector.push_back(tempVal);
}
matrix.push_back(myvector);
}
回答by SubhaBhowmik
try this. m = row, n = col
尝试这个。 m = row, n = col
vector<vector<int>> matrix(m, vector<int>(n));
for(i = 0;i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
回答by Mohit
Vector needs to be initialized before using it as cin>>v[i][j]
. Even if it was 1D vector, it still needs an initialization, see this link
Vector 在用作cin>>v[i][j]
. 即使是一维向量,它仍然需要初始化,请参阅此链接
After initialization there will be no errors, see this link
初始化后不会有错误,看这个链接
回答by serghei
Assume we have the following class:
假设我们有以下类:
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> data;
};
First of all I would like suggest you to implement a default constructor:
首先,我建议您实现一个默认构造函数:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
private:
std::vector<std::vector<int>> data;
};
At this time we can create Matrix instance as follows:
这时候我们可以创建Matrix实例如下:
Matrix one;
The next strategic step is to implement a Reset
method, which takes two integer parameters that specify the new number of rows and columns of the matrix, respectively:
下一个战略步骤是实现一个Reset
方法,该方法采用两个整数参数,分别指定矩阵的新行数和列数:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
if (rows == 0 || cols == 0) {
data.assign(0, std::vector<int>(0));
} else {
data.assign(rows, std::vector<int>(cols));
}
}
private:
std::vector<std::vector<int>> data;
};
At this time the Reset
method changes the dimensions of the 2D-matrix to the given ones and resets all its elements. Let me show you a bit later why we may need this.
此时,该Reset
方法将 2D 矩阵的维度更改为给定的维度并重置其所有元素。让我稍后告诉你为什么我们可能需要这个。
Well, we can create and initializeour matrix:
好吧,我们可以创建并初始化我们的矩阵:
Matrix two(3, 5);
Lets add info methods for our matrix:
让我们为我们的矩阵添加 info 方法:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
At this time we can get some trivial matrix debug info:
这时候我们可以得到一些简单的矩阵调试信息:
#include <iostream>
void MatrixInfo(const Matrix& m) {
std::cout << "{ \"rows\": " << m.GetNumRows()
<< ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}
int main() {
Matrix three(3, 4);
MatrixInfo(three);
}
The second class method we need at this time is At
. A sort of getter for our private data:
这时候我们需要的第二个类方法是At
. 我们私人数据的一种吸气剂:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int At(const int &row, const int &col) const {
return data.at(row).at(col);
}
int& At(const int &row, const int &col) {
return data.at(row).at(col);
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
The constant At
method takes the row number and column number and returns the value in the corresponding matrix cell:
常量At
方法获取行号和列号,并返回相应矩阵单元格中的值:
#include <iostream>
int main() {
Matrix three(3, 4);
std::cout << three.At(1, 2); // 0 at this time
}
The second, non-constant At
method with the same parameters returns a referenceto the value in the corresponding matrix cell:
At
具有相同参数的第二个非常量方法返回对相应矩阵单元格中值的引用:
#include <iostream>
int main() {
Matrix three(3, 4);
three.At(1, 2) = 8;
std::cout << three.At(1, 2); // 8
}
Finally lets implement >>
operator:
最后让我们实现>>
运算符:
#include <iostream>
std::istream& operator>>(std::istream& stream, Matrix &matrix) {
int row = 0, col = 0;
stream >> row >> col;
matrix.Reset(row, col);
for (int r = 0; r < row; ++r) {
for (int c = 0; c < col; ++c) {
stream >> matrix.At(r, c);
}
}
return stream;
}
And test it:
并测试它:
#include <iostream>
int main() {
Matrix four; // An empty matrix
MatrixInfo(four);
// Example output:
//
// { "rows": 0, "cols": 0 }
std::cin >> four;
// Example input
//
// 2 3
// 4 -1 10
// 8 7 13
MatrixInfo(four);
// Example output:
//
// { "rows": 2, "cols": 3 }
}
Feel free to add out of range check. I hope this example helps you :)
随意添加超出范围的检查。我希望这个例子可以帮助你:)
回答by Amr1318
I did this class for that purpose. it produces a variable size matrix ( expandable) when more items are added
我为此目的开设了这门课。当添加更多项目时,它会生成一个可变大小的矩阵(可扩展)
'''
'''
#pragma once
#include<vector>
#include<iostream>
#include<iomanip>
using namespace std;
template <class T>class Matrix
{
public:
Matrix() = default;
bool AddItem(unsigned r, unsigned c, T value)
{
if (r >= Rows_count)
{
Rows.resize(r + 1);
Rows_count = r + 1;
}
else
{
Rows.resize(Rows_count);
}
if (c >= Columns_Count )
{
for (std::vector<T>& row : Rows)
{
row.resize(c + 1);
}
Columns_Count = c + 1;
}
else
{
for (std::vector<T>& row : Rows)
{
row.resize(Columns_Count);
}
}
if (r < Rows.size())
if (c < static_cast<std::vector<T>>(Rows.at(r)).size())
{
(Rows.at(r)).at(c) = value;
}
else
{
cout << Rows.at(r).size() << " greater than " << c << endl;
}
else
cout << "ERROR" << endl;
return true;
}
void Show()
{
std::cout << "*****************"<<std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " <<setw(5)<< c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
void Show(size_t n)
{
std::cout << "*****************" << std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " << setw(n) << c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
// ~Matrix();
public:
std::vector<std::vector<T>> Rows;
unsigned Rows_count;
unsigned Columns_Count;
};
'''
'''
回答by Shantanu Garg
What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vectoryou have named matrix in your example.
您初始化的是一个vector 向量,因此您肯定必须在示例中命名为 matrix的原始向量中包含要插入的向量(向量术语中的“Pushed”)。
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
还有一件事,您不能使用运算符“cin”直接在向量中插入值。使用一个接受输入的变量,然后将其插入到向量中。
Please try this out :
请试试这个:
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}