如何将文件中的值输入矩阵?

时间:2016-08-18 01:38:51

标签: c++ arrays matrix

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

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

1 个答案:

答案 0 :(得分:1)

在为元素赋值之前,必须在每个向量中分配数组。

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set /A "index=0"
for /f "delims=" %%a in ('findstr /N /R "^" "%~dpn0.lst"') do (
    setlocal EnableDelayedExpansion
    for /F %%b in ("$$!random!.!index!") do (
        endlocal
        set "%%b=%%a"
    )
    set /A "index+=1"
)
> "%~dpn0.new" (
    for /f "delims=" %%a in ('set $$') do (
        set "item=%%a"
        setlocal EnableDelayedExpansion
        echo(!item:*:=!
        endlocal
    )
)

endlocal
exit /B