【问题标题】:2-dimensional vector data member二维向量数据成员
【发布时间】:2020-06-25 02:15:49
【问题描述】:

我收到 EXC BAD ACCESS 错误。不确定是什么问题。我正在尝试测试二维向量内的单元格。我希望它打印一个 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;
}

【问题讨论】:

    标签: c++ oop multidimensional-array vector


    【解决方案1】:

    在您的代码中,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
    

    【讨论】:

    • 你是最棒的!谢谢你!语法对二维向量不是很友好。
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    相关资源
    最近更新 更多