分段错误:从2d向量中随机删除元素

时间:2017-04-24 20:11:36

标签: c++ vector

给定一个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时会出现分段错误 - 因此,由于仍然存在“行”向量,所以它是否仍然不能访问任何一行?

1 个答案:

答案 0 :(得分: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 );
    }
}

我们希望确保处理空的二级向量,而不是在它们变空之后尝试从它们中删除。因此,此代码在空矢量变空后删除它。

相关问题