gpt4 book ai didi

C++将 vector 的一个元素放入另一个 vector

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:20 28 4
gpt4 key购买 nike

我正在使用 SDL 开发 RTS 游戏。我有一个木场类,其对象将从附近的树木中收集木材。在类中,我创建了一个名为 temp_trees 的 vector ,并使用传入的树对象 vector 作为构造函数的参数。

木场构造器:

woodyard::woodyard(int x, int y, int HP, int id, vector<Tree> trees)
{
...
vector<Tree> temp_trees;
for(int i = 0; i < trees.size(); i++)
{
if((trees[i].xPos - 100) / 50 >= x - 5 && (trees[i].xPos - 100) / 50 <= x + 4)
{
if((trees[i].yPos - 100) / 50 >= y - 5 && (trees[i].yPos - 100) / 50 <= y + 4)
{
temp_trees.push_back(trees[i]);
}
}
}

collect_control = 0;
no = 0;
}

collect_wood 函数:

void woodyard::collect_wood(){
if(no == 5)
{
temp_trees[collect_control].drewno -= 1;
if(temp_trees[collect_control].drewno <= 0){
collect_control++;
temp_trees.erase(temp_trees.begin());
}}


no++;
if(no >= 10){
no = 0;
}}

程序刚启动就崩溃了。任何人都可以看到这段代码中的任何错误吗??

PS:我想在构造函数中将元素从一个 vector 复制到另一个 vector 可能有问题。

最佳答案

构造函数不包含任何非法操作。

而 collect_wood(),虽然难以理解,但不包含使其崩溃的任何明显原因。

这是collect_control的值?你看看是不是< temp_trees.size() ?意识到 temp_trees.size()不断变化,因为你正在删除元素。

可能 collect_control删除后不应该递增:所有元素移回,删除后的 collect_control 已经指向下一个元素。

注意:考虑 temp_trees.erase(temp_trees.begin());是您可以用 vector 做的最低效的事情之一(删除第一个元素)。

关于C++将 vector 的一个元素放入另一个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254535/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com