用于创建矩阵的向量

Vector of Vectors to create matrix

本文关键字:向量 创建 用于      更新时间:2023-10-16

我正在尝试接受二维矩阵尺寸的输入。然后使用用户输入来填充此矩阵。我尝试这样做的方式是通过向量(向量的向量(。但是每当我尝试读取数据并将其附加到矩阵时,我都遇到了一些错误。

//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];
    }
}

每当我尝试这样做时,它都会给我一个下标超出范围的错误。有什么建议吗?

在访问任何元素之前,您必须将向量的向量初始化为适当的大小。你可以这样做:

// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));

这将创建一个大小RR CC向量的向量,填充0 .

实际上,向量的两个维度都是 0。

相反,将向量初始化为:

vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
   matrix[i].resize(CC);

这将为您提供一个维度矩阵RR * CC所有元素都设置为 0 .

我不

熟悉 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);
}

假设我们有以下类:

#include <vector>
class Matrix {
 private:
  std::vector<std::vector<int>> data;
};

首先,我想建议你实现一个默认构造函数:

#include <vector>
class Matrix {
 public:
  Matrix(): data({}) {}
 private:
  std::vector<std::vector<int>> data;
};

此时我们可以按如下方式创建矩阵实例:

Matrix one;

下一个战略步骤是实现一个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;
};

此时,Reset方法将 2D 矩阵的尺寸更改为给定的尺寸并重置其所有元素。稍后让我告诉你为什么我们可能需要这个。

好吧,我们可以创建并初始化我们的矩阵:

Matrix two(3, 5);

让我们为我们的矩阵添加信息方法:

#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;
};

此时我们可以得到一些琐碎的矩阵调试信息:

#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);
}

我们此时需要的第二类方法是 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;
};

常量 At 方法采用行号和列号,并返回相应矩阵单元格中的值:

#include <iostream>
int main() {
  Matrix three(3, 4);
  std::cout << three.At(1, 2); // 0 at this time
}

具有相同参数的第二个非常量 At 方法返回对相应矩阵单元格中值的引用

#include <iostream>
int main() {
  Matrix three(3, 4);
  three.At(1, 2) = 8;
  std::cout << three.At(1, 2); // 8
}

最后让我们实现>>运算符:

#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;
}

并对其进行测试:

#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 }
}

随意添加超出范围检查。我希望这个例子可以帮助你:)

试试这个。 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;
}

Vector 需要先初始化,然后再将其用作cin>>v[i][j]。即使是一维向量,它仍然需要初始化,请参阅此链接

初始化后不会有错误,请参阅此链接

您初始化的是向量的向量,因此您绝对必须在示例中命名矩阵的原始向量中包含要插入的向量(向量术语中的"推送"(。

还有一件事,您不能使用运算符"cin"直接在向量中插入值。使用一个接受输入的变量,然后在向量中插入相同的变量。

请尝试一下:

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 
}

我为此做了这个课程。 当添加更多项目时,它会产生一个可变大小的矩阵(可扩展(

'

''

#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;
};
'

''