有关矩阵的代码错误导致分段错误(内核转储)
Error in code about matrix resulting in segmentation fault (core dumped)
救命!另一个可能很简单的错误,但我找不到解决方案。编译时不会出现错误消息,也没有建议,但我已经尝试了许多不同的方法。我是编程新手。
#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);
}
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)