我收到EXC不良访问错误。不确定是什么问题。我正在尝试测试2d 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/

10-10 21:23