首页 > 解决方案 > 初始化后的向量 at() 超出范围错误

问题描述

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

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

下一个目标是将一些 Ants 放置在向量中的指定点,而我的 ant 类继承自昆虫类。这是使用 .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;是 Colony 类中的私有成员变量。我的想法是该向量以某种方式超出了范围,但我不确定如何修复。提前感谢任何提示/建议

标签: c++classinheritancevector

解决方案


initBoard()中,您声明了一个名为您正在填充的局部变量gameBoard,而不是同名的类成员。

更改此行:

vector<Insect*> gameBoard (10, nullptr);

为此:

gameBoard.resize (10, nullptr);

话虽如此,由于您在编译时知道元素的数量,因此请考虑使用固定数组而不是 a std::vector,例如:

std::array<Insect*, 10> gameBoard;

无论哪种方式,您都应该存储std::unique_ptr<Insect>元素而不是原始Insect*指针,例如:

gameBoard.at(position).reset(new Ant(position));

或者:

gameBoard.at(position) = std::make_unique<Ant>(position);

推荐阅读