首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2维向量数据成员

2维向量数据成员
EN

Stack Overflow用户
提问于 2020-06-25 10:15:50
回答 1查看 46关注 0票数 2

我收到一个EXC错误访问错误。不确定问题出在哪里。我正在尝试测试2d向量中的细胞。我希望它打印一个0的20x20的网格

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-25 10:19:07

在您的代码中,cellVec是默认初始化的,并且不包含任何元素。然后尝试访问它的元素,如cellVec[i],则会导致UB。

您可以在member initializer list中将cellVec初始化为包含20个元素,例如

代码语言:javascript
复制
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);
    }
}

或直接

代码语言:javascript
复制
Board() : cellVec(20, std::vector<Cell>(20)) {}
//        initialize cellVec as containing 20 std::vector<Cell>(20)s which containing 20 Cells
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62566851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档