c++ - 二维 vector 数据成员

标签 c++ oop multidimensional-array vector

我收到 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/

相关文章:

c++ - Dlib 将自训练检测器应用于视频 (mmod_dnn)

c++ - 如何创建可变参数模板字符串格式化程序

javascript - 从 C# 到 JavaScript - 使用类实例

c - 在二维数组中存储字符串(char*)

c++ - 如何使用 C++11 lambda 作为 boost 谓词?

c++ - 用于多个目标的 2D 瓦片 map 寻路

arrays - 如何在 Swift 的 View Controller 类中与 Collection View 委托(delegate)共享数据

java - 在不使用比较器的情况下按不同属性比较对象

c++ - 指向运行时固定大小数组的指针是否合法?

php - 在 PHP 中对多维数组进行排序?