我收到 EXC BAD ACCESS 错误。不确定是什么问题。我正在尝试测试二维 vector 内的细胞。我希望它打印 0 的 20x20 网格
struct Cell {
int test;
Cell(): test(0) {}
};
class Board {
public:
Board() {
for (int i = 0; i < 20; i++) {
Cell temp;
cellVec[i].resize(20, temp);
}
}
friend ostream& operator<<(ostream& out, const Board& boardPrint) {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
out << boardPrint.cellVec[i][j].test;
}
}
return out;
}
private:
vector< vector<Cell> > cellVec;
};
int main() {
Board newBoard;
cout << newBoard;
}
最佳答案
在您的代码中,cellVec
已默认初始化且不包含任何元素。然后尝试像 cellVec[i]
一样访问它的元素会导致 UB。
您可以将 cellVec
初始化为包含 member initializer list 中的 20 个元素,例如
Board() : cellVec(20) {
// initialize cellVec as containing 20 default-initialized std::vector<Cell>s which containing no elements
for (int i = 0; i < 20; i++) {
Cell temp;
cellVec[i].resize(20, temp);
}
}
或者直接
Board() : cellVec(20, std::vector<Cell>(20)) {}
// initialize cellVec as containing 20 std::vector<Cell>(20)s which containing 20 Cells
关于c++ - 二维 vector 数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566851/