分段故障核心转储,矢量嵌套在矢量中
Segmentation Fault Core Dumped with a Vector Nested in a 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;
}
}
}
}
现在它似乎能够创建除最后一个向量之外的所有内容,然后我得到了分割错误。有关更完整的源代码,请 http://pastebin.com/AB59bPMR .
只需使用方法resize()
就可以使矩阵有多大
matrix.resize(rows, vector < int >(columns));
在 for 循环中犯了一个简单的错误i <= columns
应该与行i < columns
相同。我也不应该从列和行变量中减去 1。
rows = rows - 1;
columns = columns - 1;
应该是
rows = rows;
columns = columns;
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++) {
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- 使用许多嵌套的#include语句对编译器错误进行故障排除
- 分段故障核心转储,矢量嵌套在矢量中
- C++:使用嵌套的 if/else 语句循环进行故障排除