2016-06-08 78 views
0

我正在尝试使用标准库向量为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

+0

那么,你是否在调试器中遍历代码并查看错误的位置? – OldProgrammer

+0

@OldProgrammer分段错误(核心转储)是我所得到的。 – Noah

+1

这听起来像你可能需要学习如何使用调试器来遍历代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

回答

4

只需使用方法resize()作基质你想有多大

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

我使用的储备功能应该做同样的事情? 'v.reserve(列);和v [i] .reserve(rows); ' – Noah

+2

不,保留和调整大小是不同的。你使用的是错误的。 – kfsone

+0

@kfsone使用调整大小,相同的结果进行测试(不像以前那样工作相同的问题)。我最初使用的是调整大小,但一旦我开始遇到程序问题,就将其更改为预留。你是对的,我读了调整大小,我应该使用它,改变它在我的代码。我仍然有Segmentation Fault问题 – Noah

1

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

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

应该已经

rows = rows; columns = columns;

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++) 

你会再尝试过去访问数组的结尾:em的第一个元素(元素[0]) pty(大小== 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++) {