2-dimensional vector data member

Viewed 55

I am getting an EXC BAD ACCESS error. Not sure what the problem is. I am trying to test the cells inside the 2d vector. I would like it to print a grid of 0's 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;
}
1 Answers

In your code cellVec is default-initialized and contains no elements. Then trying to access element of it like cellVec[i] leads to UB.

You can initialize cellVec as containing 20 elements in member initializer list, e.g.

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

Or directly

Board() : cellVec(20, std::vector<Cell>(20)) {}
//        initialize cellVec as containing 20 std::vector<Cell>(20)s which containing 20 Cells
Related