尝试访问空向量时出现分段错误

Segmentation fault while trying to access empty vector

所以我制作了一个二维字符数组,但每次我尝试访问它时都会出现分段错误,我无法弄清楚原因。

std::vector<std::vector<char>> matrix_;

//Filling it with space ' ' characters
std::vector<char> aRow;
matrix_.resize(height_, aRow);
for (std::vector<char> row : matrix_) {
    row.resize(width_, ' ');
}

std::cout << matrix_[0][0]; //Segmentation fault here

for 中使用 auto&& row : matrix_(注意添加的引用)来获取您要查找的每一行的引用。

如您所见,它会创建一个副本,调整其大小并丢弃结果。

不必对此过于悲观,您还可以使用合适大小的行来调整每一列的大小。不需要 for 循环。

std::vector<char> aRow(width_, ‘ ‘);
matrix_.resize(height_, aRow);