C++将向量的一个元素推到另一个向量

C++ puttting one element of vector to another vector

本文关键字:向量 元素 一个 另一个 C++      更新时间:2023-10-16

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

木材加工厂建造商:

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:我想在构造函数中将元素从一个向量复制到另一个向量可能有问题。

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

collect_wood()虽然难以理解,但并没有包含任何导致它崩溃的明显原因。

collect_control的值是多少?你检查它是否是< temp_trees.size()吗?请注意,temp_trees.size()在擦除元素后一直在变化。

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

注意:考虑一下temp_trees.erase(temp_trees.begin());是使用向量(删除第一个元素)所能做的最低效的事情之一。

在woodyard构造函数中,您正在声明一个临时的、函数范围的变量"temp_trees"。

woodyard::woodyard(int x, int y, int HP, int id, vector<Tree> trees)
{
...
vector<Tree> temp_trees;

如果你有一个名为temp_trees的向量成员,这个声明会隐藏它。所以你的成员函数看不到相同的向量:

void woodyard::collect_wood(){
if(no == 5)
{
 temp_trees[collect_control].drewno -= 1;

此外,如果没有看到其余的代码,我不知道如何确保向量中至少有"collect_control"成员。

#include <assert.h>
...
assert(collect_control < temp_trees.size());

或者如果你使用的是visualstudio,你可以做

if(collect_control >= temp_trees.size())
    DebugBreak();

"size()"是一个基于1的值,但数组索引运算符是基于零的。这意味着,当向量中有一个条目时,它将是向量[0]。如果向量为空,则向量[0]是非法的——它不存在。空的大小表示为0。size必须始终大于您试图访问的元素索引。