gpt4 book ai didi

c++ - 段错误 : randomly removing elements from 2d vector

转载 作者:行者123 更新时间:2023-11-30 05:14:04 25 4
gpt4 key购买 nike

给定一个二维 vector ,我想随机检索然后删除一个元素,重复这个过程直到 vector 为空。

但是,我的代码在每次运行时都在循环中的不同点返回一个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 时出现段错误 - 因此,既然仍然存在“行” vector ,它不应该是仍然可以访问任何行吗?

最佳答案

我现在手边没有编译器,但我想你正在寻找类似的东西:

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 );
}
}

我们要确保我们处理的是空的二级 vector ,而不是在它们变空后试图从中删除。因此,此代码在空 vector 变空后将其移除。

关于c++ - 段错误 : randomly removing elements from 2d vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com