71

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

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

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

4

8 回答 8

197

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

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

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

于 2012-09-11T20:33:20.767 回答
86

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

相反,将向量初始化为:

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

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

于 2012-09-11T18:19:57.500 回答
12

我不熟悉 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);
}
于 2012-09-11T18:25:18.513 回答
4

假设我们有以下类:

#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实例:

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

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

于 2019-11-26T21:26:50.177 回答
2

试试这个。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;
}
于 2017-06-27T11:44:19.443 回答
1

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

初始化后不会报错,看这个链接

于 2019-03-09T11:59:07.967 回答
0

您初始化的是vectors的向量,因此您必须在示例中命名为 matrix的原始向量中包含一个要插入的向量(向量术语中的“Pushed”) 。

还有一件事,您不能使用运算符“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 
}
于 2018-06-29T20:16:57.897 回答
0

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

'''

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

'''

于 2019-12-02T02:59:35.100 回答