分割故障核心转储嵌套在矢量中的矢量

时间:2016-06-08 17:18:06

标签: c++ c++11 vector segmentation-fault

我正在尝试使用标准库向量为Matrix创建一个类。我在向量中使用向量来设置Matrix,一个向量表示列,另一个(向量)表示行和存储在行中的值。这是变量和构造函数。

变量:

 int columns;
 int rows;
 std::vector<std::vector<int> > v;

构造

 Matrix(int a, int b){
std::cout << "Input Recieved.. Construct Began" << std::endl;
rows = a;
columns = b;
// Subtract one to put them in a proper array format
rows = rows - 1;
columns = columns - 1;
//Creates the columns
v.reserve(columns);
//Creates the Rows .. Code is ran for every column, this is where the values are set
for(int i = 0; i <= columns; i++){

  v[i].reserve(rows);
  std::cout << "Column " << i  + 1 << " Created, with " << rows + 1<< " Rows" << std::endl;


  //Sets the values of the rows .. is ran for every column
  for(int e = 0; e <= rows; e++){
    if(i == 19){
      std::cout << "Column 20 row setting has begun" << std::endl;
    }


    v[i][e] = 2;

    if(i == 19){
    std::cout << "Made it past the line" << std::endl;
  }

    std::cout << "Row " << e + 1 << " Set in Column " << i + 1<< ", with Value " << v[i][e] << std::endl;

    if(i == 19){
      std::cout << "Column 20 row setting has finished" << std::endl;
    }
  }



}

}

现在它似乎能够创建除最后一个向量之外的所有内容,然后我得到了分段错误..对于更完整的源代码,有http://pastebin.com/AB59bPMR

3 个答案:

答案 0 :(得分:4)

只需使用resize()方法制作一个矩阵你想要的大小

matrix.resize(rows, vector < int >(columns));

答案 1 :(得分:1)

使用for循环i <= columns犯了一个简单的错误应该i < columns与行相同。另外,我不应该从列和行变量中减去1。

rows = rows - 1; columns = columns - 1;

应该

rows = rows; columns = columns;

答案 2 :(得分:1)

columns = columns - 1;
//Creates the columns
v.reserve(columns);
//Creates the Rows .. Code is ran for every column, this is where the values are set
for(int i = 0; i <= columns; i++){

让我们看一下1x1矩阵的简单情况:

columns = columns - 1 => columns = 0
v.reserve(0);    // should be resize
for (int i = 0; i <= 0; i++)

然后,您将尝试访问数组的末尾:空(size == 0)数组的第一个元素(element [0])。对于任何其他值也是如此 - 您可以访问数组的末尾。

保持列不变。

Matrix(int a, int b){
    std::cout << "Input Recieved.. Construct Began" << std::endl;
    rows = a;
    columns = b;

    //Creates the columns
    v.resize(columns);

    //Creates the Rows .. Code is ran for every column, this is where the values are set
    for(int i = 0; i < columns; i++) {