c++ - 初始化后的向量 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 类中的私有成员变量。我的想法是该向量以某种方式超出了范围,但我不确定如何修复。提前感谢任何提示/建议
解决方案
在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);
推荐阅读
- php - 使用特定术语进行 wordpress 循环
- java - JButton上的Java ImageIcon重复图像
- python - UDP 使用以太网电缆点对点通信不起作用?
- c# - Fody 在参考项目上编织?
- python - 将 ndarray 转换为 Base64
- sorting - 使用数字列开始和结束分隔符对文件进行排序
- html - 如何设置子div的宽度sroll div的全宽?
- python-3.x - 使用 scipy.integrate.solve_bvp 将初始值问题调整为边界值问题?
- html - 元素出现乱序
- javascript - StateSave 在 Yajra 数据表上的外部过滤器中不起作用