2017-04-24 107 views
1

隨機刪除元素,我想隨機檢索和然後刪除一個元素,重複此過程,直到所述載體是空的。分段故障:從給定的2D矢量2D矢量

但是,我的代碼返回時,在循環中運行,在不同的點每次Segmentation fault: 11錯誤。這告訴我代碼試圖從一個不再存在的索引中檢索一個元素,並且我一直在想如何解析索引或者不正確地刪除元素。

如何解決這個問題有什麼建議?

#include <vector> 
#include <iostream> 

int main(void) { 

    int X_LENGTH = 4; 
    int Y_LENGTH = 4; 
    std::vector<std::vector<long> > arrayCellDistance(X_LENGTH, std::vector<long>(Y_LENGTH, 0)); 

    // Assign values to array, print them out in order 
    for (int i = 0; i < X_LENGTH; i++) { 
     for (int j = 0; j < Y_LENGTH; j++) { 
      arrayCellDistance[i][j] = (i+j)/2 + i*j; 
      std::cout << "arrayCellDistance[" << i << "][" << j << "] = " << arrayCellDistance[i][j] << std::endl; 
     } 
    } 

    std::cout << "===============================================" << std::endl; 

    int x, y; 
    srand(time(NULL)); 

    while (!arrayCellDistance.empty()) { 

     y = (rand() % (int)(arrayCellDistance.size())); // Rand from 0 to number of rows 
     x = (rand() % (int)(arrayCellDistance[y].size())); // Rand from 0 to number of columns in row 

     // 'Retrieve' value from array and then delete this value 
     std::cout << "arrayCellDistance[" << x << "][" << y << "] = " << arrayCellDistance[x][y] << std::endl; 

     arrayCellDistance[y].erase(arrayCellDistance[x].begin() + 1); // Remove element 

    } 

    return 0; 
} 

當打印取出後,在矩陣中,我得到這樣的輸出:

arrayCellDistance[0][1] = 0 
0 1 1 0 
2 3 5 
1 3 6 8 
1 5 8 12 
arrayCellDistance[2][2] = 6 
0 1 1 0 
2 3 5 
1 6 8 
1 5 8 12 
arrayCellDistance[1][1] = 3 
0 1 1 0 
2 5 
1 6 8 
1 5 8 12 
arrayCellDistance[2][2] = 8 
0 1 1 0 
2 5 
1 8 
1 5 8 12 
arrayCellDistance[1][0] = 2 
Segmentation fault: 11 

正如你所看到的,有當程序試圖刪除2第二行中的分段錯誤 - 因此,由於仍存在「行」向量,它是否應該仍然無法訪問任何行?

+2

'arrayCellDistance.size()+ 1 - 1'?爲什麼不簡單地'arrayCellDistance.size()'? – Borgleader

+0

考慮你的條件語句'而(!arrayCellDistance.empty())'這是否處理,其中第一級矢量不爲空,但第二級矢量其中之一,然後嘗試從第二級中刪除元素的情況下向量? –

+0

@Borgleader良好抓 - 隨機函數產生在範圍內的整數'[0,arrayCellDistance.size()]'時'+ 1'被包括,也試圖訪問索引超出範圍,因此'-1'加入到改變至'[0,arrayCellDistance.size() - 1]' –

回答

1

我沒有編譯器方便的權利,但我認爲你正在尋找的東西,如:

while (!arrayCellDistance.empty()) 
{ 
    y = (rand() % (int)(arrayCellDistance.size())); // Rand from 0 to number of rows 

    if(arrayCellDistance[y].empty()) 
    { 
     // Error - Contained empty second-level vector initially. 
     break; 
    } 

    x = (rand() % (int)(arrayCellDistance[y].size())); // Rand from 0 to number of columns in row 

    // Get value from array and display 
    std::cout << "arrayCellDistance[" << x << "][" << y << "] = " << arrayCellDistance[x][y] << std::endl; 

    // Remove element of second-level vector 
    arrayCellDistance[y].erase(arrayCellDistance[y].begin() + x); 

    // Remove empty first-level vector 
    if(array[y].empty()) 
    { 
     arrayCellDistance.erase(arrayCellDistance.begin() + y); 
    } 
} 

我們要確保我們正在處理空的第二級矢量,而不是試圖從抹去他們變得空空如也。所以,這段代碼在變空後刪除一個空的向量。

+0

你是美麗的人。謝謝! –

+0

沒問題:)很高興我能幫上忙 –