创建大小为其他两个矩阵大小的矩阵时超出范围

Out of range when creating a matrix whose sizes are sizes of two other matrices

本文关键字:范围 两个 其他 小为 创建      更新时间:2023-10-16

假设我有两个矩阵,称为 A 和 B,我想创建一个新的矩阵 C,其中 C 的行数等于矩阵 A 和 B 的行数的乘积。C 的列数也等于 A 和 B 的列数的乘积。

当任何矩阵 A 或 B 是空矩阵时,我的程序不起作用。

我尝试将矩阵 A 和 B 的大小设置为与零不同的值,该程序有效。

  // this function "creates" and returns a matrix of the size mentioned in parameters

 vector<vector<int>> CreateMatrix (int number_of_rows, int number_of_columns) {
  return vector<vector<int>>(number_of_rows, vector<int> (number_of_columns));
 } 
  int main()
  {
    vector<vector<int>> a;
    vector<vector<int>> b;
    int no_rows = a.size() * b.size(); // multiplies no. of rows A and B
    int no_cols = a.at(0).size() * b.at(0).size(); // multiplies number of columns of A and B
   auto c = CreateMatrix(no_rows, no_cols).
   cout << c.size(); 

我预计程序会打印"0",因为这将是矩阵 C 的行数,但它不会崩溃。

    vector<vector<int>> a;
    vector<vector<int>> b;
    int no_cols = a.at(0).size() * b.at(0).size(); // multiplies number of columns of A and B

在这里,您可以访问两个空向量的第一个元素,因此自然会崩溃。