c++ - vector 中嵌套 vector 的分段故障核心转储

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

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

变量:

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



}

}

现在它似乎能够创建除最后一个 vector 之外的所有内容,然后我得到了段错误。有关更完整的源代码,请参见 http://pastebin.com/AB59bPMR .

最佳答案

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

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

关于c++ - vector 中嵌套 vector 的分段故障核心转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708952/

相关文章:

c++ - 如何检查成员运算符(类型)?

C++ 一个 "string made out of digits"的衬里

python - 如何用python写numpy : b = sum(v) - a as an implicitly elementwise (vector) computation?

boost - 如何创建进程间容器的 boost 进程间向量?

c++ - Windows 8 中的开发人员 C : gcc Internal Error

c++ - 如何使用 alglib 创建 double 矩阵?

c++ - GCC 4.4 fails to link valid C++11 code, when options are -std=C++0x -O0

c++ - 包含引用的对象 vector

c++ - 奇怪的 VS2012 C++ 解析

c++ - LNK2019未解析的外部符号求助