我收到一个EXC错误访问错误。不确定问题出在哪里。我正在尝试测试2d向量中的细胞。我希望它打印一个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;
}发布于 2020-06-25 10:19:07
在您的代码中,cellVec是默认初始化的,并且不包含任何元素。然后尝试访问它的元素,如cellVec[i],则会导致UB。
您可以在member initializer list中将cellVec初始化为包含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 Cellshttps://stackoverflow.com/questions/62566851
复制相似问题