C++将向量的一个元素推到另一个向量
C++ puttting one element of vector to another vector
我正在使用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必须始终大于您试图访问的元素索引。
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C