有关矩阵的代码错误导致分段错误(内核转储)

Error in code about matrix resulting in segmentation fault (core dumped)

本文关键字:错误 分段 内核 转储 代码      更新时间:2023-10-16

救命!另一个可能很简单的错误,但我找不到解决方案。编译时不会出现错误消息,也没有建议,但我已经尝试了许多不同的方法。我是编程新手。

#ifndef __MATRIX_H__
#define __MATRIX_H__
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include "Vector.h"
using namespace std;
typedef unsigned int uint;
//Matrix class to handle basic linear algebra operations.
template<typename T>
class Matrix
{
public:
vector<vector<T> > elements;
uint shape[2];
// Constructors
Matrix();
Matrix(uint, uint);
Matrix(vector<vector<T> >);
Matrix(string);
//Print vector elements.
void print() const;
//Print vector shape.
void printshape() const;
//Append a vector to the last row.
void push_back(vector<T>);
//Check if matrix has same shape to other matrix.
bool has_same_shape(Matrix<T>&) const;
//Save matrix to a text file with string filename as parameter.
void savetext(string) const;
//Indexing operator that returns the row as a Vector class.
vector<T> operator[] (uint);
//Comparison operator.
bool operator== (Matrix<T>&);
//Matrix transpose.
Matrix<T> transpose();
//Destructor.
~Matrix();
};
//Default Constructor.
template<typename T>
Matrix<T>::Matrix() {};
// Constructor for zero matrix with shape = num_row-by-num_col.
template<typename T>
Matrix<T>::Matrix(uint num_row, uint num_col){
for(uint i = 0; i <= num_row; i++){
for(uint j = 0; j <= num_col; j++){
elements[i].push_back(0);
}
}
shape[0] = num_row;
shape[1] = num_col;
}

我没有包含代码的其他部分,因为它们大多是空的/在注释中

elements[i].push_back(0);你的数组访问是越界的,因为你从不向elements添加任何内容,所以此时它是空的。

一个简单的解决方案是在外循环中添加一个新的向量:

for(uint i = 0; i <= num_row; i++){
//add new vector with emplace back
elements.emplace_back();
for(uint j = 0; j <= num_col; j++){
elements[i].push_back(0);
}
}