如何将值从文件输入到矩阵中

How do I input values from a file into a matrix?

本文关键字:输入 文件      更新时间:2023-10-16

我想使用函数将特定的值输入到矩阵中,但由于matInit函数中的一些错误,我一直收到分割错误。无论是否将其设置为bar.col[I],都会收到此错误。els[k]=0(如下所示)或者save bar。Col [i]作为一个数组,用k值做一个for循环。我感觉分割错误是由于尺寸不匹配,但我不知道我做错了什么。我还必须通过结构输入值,因为这是这个项目的要求。

#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
struct Vector {
  float* els;  
  int len;
};
struct Matrix {
  Vector* col; 
  int ncols;    // total number of columns in matrix
};
// Initializer functions for our structures
Vector vecInit(int);     // Provided below
Matrix matInit(int,int); // ** You must complete this
// Overloaded operators
Vector operator+(Vector,Vector);  // Provided below
Vector operator*(float,Vector);   // ** You must write this 
Vector operator*(Matrix,Vector);  // ** You must write this
istream& operator>>(istream&, Vector&); // Provided below
istream& operator>>(istream&, Matrix&); // ** You must write this
// Other Vector functions
float vecDot(Vector,Vector); // ** You must write this
//    main code 
// **** This must be left unchanged in your submission *****
int main(void) {
  int m,n,nv,nw;
  ifstream fin("mat.def");
  if (!fin.is_open()) {
    cout << "Cannot find file mat.def!" << endl;
  }
  else {
   // Load details of matrix M from file
    fin >> m >> n;
    Matrix M = matInit(m,n);
fin >> M;
cout << "M is " << m << "x" << n << endl;

  }
  return 0;
}
// *****************************************************
//    Support function definitions 
// ** Provided Code.  Do not change **
// Vector structure initializer
// *** Partially provided code.  Change as needed below ***
//     Matrix structure initializer
    Matrix matInit(int m, int n) {
  Matrix bar;
bar.ncols = n;
bar.col = new Vector[m];  

for (int i=0;i<n;i++) {
for (int k=0;k<m;k++) {
bar.col[i].els[k]=0;
}
}



  return bar;
}

istream& operator>>(istream& input, Matrix& M) {
int leng=M.col[0].len;

for (int i=0;i<M.ncols;i++) {
for (int k=0;k<leng;k++) {
input >> M.col[i].els[k];
}
}
  return input;
}

在为每个vector的元素赋值之前,必须先为其分配数组。

Matrix matInit(int m, int n) {
  Matrix bar;
  bar.ncols = n;
  bar.col = new Vector[n]; // use n instead m for consistency
  for (int i=0;i<n;i++) {
    bar.col[i].els = new float[m]; // add this line to allocate arrays
    for (int k=0;k<m;k++) {
      bar.col[i].els[k]=0;
    }
  }
  return bar;
}