【问题标题】:Vector at() out of range error after initializing初始化后的向量 at() 超出范围错误
【发布时间】:2020-09-03 17:20:51
【问题描述】:

大家好(第一次发帖到这里)。 我正在开发一个基于文本的 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;
}

下一个目标是将一些蚂蚁放置在向量中的指定点上,我的蚂蚁类继承自昆虫类。这是我在使用 .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&lt;Insect*&gt; gameBoard; 是 Colony 类中的私有成员变量。我的想法是该向量不知何故超出了范围,但我不确定如何修复。提前感谢任何提示/建议

【问题讨论】:

  • gameBoard 是函数 initBoard 的一个局部变量,它隐藏了同名的成员变量(你说的那个)。这就是您应该提供minimal reproducible example 的原因。
  • 谢谢,出于某种原因,我在 init 函数中创建了一个新向量。在构造函数中正确初始化后,我能够让它工作。

标签: c++ class inheritance vector


【解决方案1】:

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

改变这一行:

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

改为:

gameBoard.resize (10, nullptr);

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

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

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

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

或者:

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

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2021-07-08
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多