【发布时间】:2012-03-27 20:57:44
【问题描述】:
我目前正在研究一种从文件中加载一堆不同 NPC 并将其加载到我的游戏中的方法。我的所有东西都可以正常使用数组,但我想将其更改为使用向量,因为我可以更改大小以防我需要比数组中可用空间更多的 NPC,所以如果我不只是有一个大部分为空的数组目前我不需要很多NPC。请注意,以下代码来自测试程序,而不是我的实际编程。我做到了,所以我不会不小心弄乱整个项目。
int main()
{
char input;
bool Running = true;
NPC Creatures[MAX_NPCS];
//InitCreatures loads the X, Y and Type from the file. I know with vectors I have to
//resize it as I go along, Which would be included in the function.
if(Creatures[MAX_NPCS].InitCreatures(Creatures) == false)
{
Creatures[MAX_NPCS].CleanUp(Creatures);
return 0;
}
while(Running == true)
{
cout << "(C)heck an NPC, (A)ttack and NPC or (E)xit the program\n";
cin >> input;
switch(input)
{
case 'C': Creatures[MAX_NPCS].Check(Creatures); break;
case 'c': Creatures[MAX_NPCS].Check(Creatures); break;
//The Check function just shows the X, Y and Type of the NPC
case 'A': Creatures[MAX_NPCS].Attack(Creatures); break;
case 'a': Creatures[MAX_NPCS].Attack(Creatures); break;
//Attack shows X, Y and type and then removes that NPC from the array.
case 'E': Running = false; break;
case 'e': Running = false; break;
default: cout << "That was not a valid input\n"; break;
}
}
Creatures[MAX_NPCS].CleanUp(Creatures);
cout << "Exiting\n";
system("PAUSE");
return 0;
}
我真正遇到的唯一问题是让 Main 从向量运行 NPC 类函数,而不是像现在这样使用数组。我可以轻松地更改我正在调用的函数中的其他内容以接受向量并正确处理它。
当我尝试使用向量来运行函数时,我只有在遇到这样的情况时才能调用它们:
Creatures[1].Attack(Creatures);
当然,当我这样调用它们时,值不会正确返回,而且我通常会收到错误消息,此外,我不知道当前地图将加载多少个 NPC,如果有的话。
对此的任何帮助将不胜感激。我意识到在编程方面我是一个新手,尤其是在 Vectors 方面。如果需要我的功能代码,我很乐意发布。
【问题讨论】:
-
呃,像
Creatures[MAX_NPCS]这样的访问是未定义的行为。您最多只能使用MAX_NPCS-1的索引。 -
哦,糟糕,很好。这也是我想要向量的原因。但我觉得我没有正确理解它们。无论如何,这些功能都有保护措施,可以防止您添加过多的 NPC 并正确执行:P
-
std::vector只不过是一个很好的打包动态数组。只需将.push_back的东西放入其中,并通过正常的数组访问 (operator[]) 获取它们。你的编程书是怎么说的? -
是的,基本上我的理解是向量是一个可调整大小的数组。这就是为什么我想在这个程序中使用它。因为我不知道每张地图会有多少个NPC。那么我将如何从向量中运行我的函数呢?当前的数组设置可以很好地存储 NPC 的 X、Y 和类型。但是我不能让向量调用命令,除非我事先指定有多少个 NPC,直到调用 InitCreatures 才知道。
标签: c++ arrays class function vector