2017-04-24 186 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

没问题:)很高兴我能帮上忙 –