简体   繁体   English

在C ++中初始化矩阵时出现分段错误(内核已转储)

[英]Segmentation fault (core dumped) when initializing a matrix in c++

I'm getting a Segmentation fault (core dumped) error when executing the program that instantiate a class Matrice and creating it in its constructor. 执行实例化类Matrice的程序并在其构造函数中创建该程序时,出现Segmentation fault (core dumped)错误。

here is my simple code: 这是我的简单代码:

#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>

class Matrice{
public:
  std::vector<std::vector<int> > mat;

  Matrice(){
    for(int i=0; i < 3; ++i) {
      for(int j=0; j < 2; ++j) {
        mat[i][j] = rand()%(10-0)+0;
      }
    }
  }
};


int main(){
  Matrice mat1;
  return 0;
}

can someone enlighten me. 有人可以启发我。

You need to resize your matrix before accessing elements: 您需要在访问元素之前调整矩阵大小:

mat.resize(3);
for( int i=0; i < 3; ++i)
{
  mat[i].resize(2);
}
Matrice(){
    for(int i=0; i < 3; ++i) {
        mat.push_back(std::vector<int>());
        for(int j=0; j < 2; ++j) {
            mat[i].push_back(rand()%(10-0)+0);
        }
    }
}

Edit: 编辑:

Explanation: vectors require the push_back function call to add an element to the end of the vector and will automatically reallocate space for the vector if it goes over the size originally allocated for the vector. 说明:向量需要push_back函数调用才能在向量的末尾添加一个元素,并且如果向量超过了最初为向量分配的大小,则会自动为向量重新分配空间。 Since it is a vector of vectors, you first need to push back an arbitrary vector, then at each arbitrary vector stored in mat[i], we push_back the random integer value needed. 由于它是向量的向量,因此您首先需要推回任意向量,然后在存储在mat [i]中的每个任意向量上,我们push_back所需的随机整数值。

You are using std::vector incorrectly. 您使用的std::vector错误。 Please see https://en.cppreference.com/w/cpp/container/vector/operator_at 请参阅https://en.cppreference.com/w/cpp/container/vector/operator_at

The [] operator returns a reference to an existing value. []运算符返回对现有值的引用。 Unlike std::map , it does not insert a new value. std::map不同,它不会插入新值。 Use std::vector::push_back() to add elements to a vector. 使用std::vector::push_back()将元素添加到向量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM