2016-06-08 57 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++) {