初始化后向量at()超出范围错误

大家好(首先在此处发布SO)。 我正在开发一个基于文本的C ++游戏(Ants vs Some Bees),作为一个附带项目,在这里我有一个在Init函数中初始化的Insect指针向量。

void Colony::initBoard()
{
    vector<Insect*> gameBoard (10, nullptr);

    //check to see that vector is properly intialized
    for (auto &it : gameBoard)
    {
        std::cout << it << std:: endl;
    };
    //check the size
    cout << gameBoard.size() << endl;
}

下一个目标是将一些蚂蚁放置在向量中的指定点,而我的蚂蚁类继承自昆虫类。这是使用.at()方法时出现向量超出范围错误的地方,并且向量显示为零。

void Colony::createAnt()
{   
    int position = 0;
    cout << "Where do you want to set your Ant? " << endl;
    cin >> position;
    //checking for size (0 here for some reason)
    cout << gameBoard.size() << endl;

    ...//validation stuff done here, not relevant to post

    gameBoard.at(position) = new Ant(position);
    isOccupied = true;
}

在main中运行此代码时,调用init函数时得到的大小为10,而调用place ant时得到的大小为0,我不确定为什么。

到目前为止,我的主要功能只是测试该功能的功能。

    Colony col;
    col.initBoard();
    col.createAnt();

vector<Insect*> gameBoard; is the private member variable in the Colony class. My thoughts is that the vector is somehow going out of scope, but I am not sure how to fix. Thanks in advance for any tips/suggestions

评论