gpt4 book ai didi

c++ - 映射 "RABBIT"字符串调用new "RABBIT"()

转载 作者:行者123 更新时间:2023-11-30 03:42:47 26 4
gpt4 key购买 nike

我必须用兔子、松鼠、狼和猎豹填充我的网格。我正在寻找字符串到类型对象的映射

populate("CHEETAH", 2);
populate("WOLF", 3);
populate("SQUIRREL", 10);
populate("RABBIT", 10);

目前,我有这个重复的代码,我想摆脱它。

CELL grid[GRIDHEIGHT][GRIDWIDTH];

void populate()
{
int num_rabbits = 0, num_squirrels = 0, num_wolves = 0, num_cheetahs = 0;
int random, randX, randY;
srand((int)time(NULL));

while (num_rabbits < 10)
{
randX = rand() % GRIDHEIGHT;
randY = rand() % GRIDWIDTH;

if (!(grid[randX][randY].Has_An_Animal()))
{
grid[randX][randY].animal = new RABBIT();
num_rabbits++;
}
}

while (num_squirrels < 10)
{
randX = rand() % GRIDHEIGHT;
randY = rand() % GRIDWIDTH;

if (!(grid[randX][randY].Has_An_Animal()))
{
grid[randX][randY].animal = new SQUIRREL();
num_squirrels++;
}
}

while (num_wolves < 3)
{
randX = rand() % GRIDHEIGHT;
randY = rand() % GRIDWIDTH;

if (!(grid[randX][randY].Has_An_Animal()))
{
grid[randX][randY].animal = new WOLF();
num_wolves++;
}
}

while (num_cheetahs < 2)
{
randX = rand() % GRIDHEIGHT;
randY = rand() % GRIDWIDTH;

if (!(grid[randX][randY].Has_An_Animal()))
{
grid[randX][randY].animal = new CHEETAH();
num_cheetahs++;
}
}
}//end

最佳答案

我认为一个简单的方法是实现一个模板函数。

template <typename T>
void populate(int maxPop) {
int i = 0;

while (i < maxPop)
{
randX = rand() % GRIDHEIGHT;
randY = rand() % GRIDWIDTH;

if (!(grid[randX][randY].Has_An_Animal()))
{
grid[randX][randY].animal = new T();
i++;
}
}
}

然后简单地调用具有适当类型的函数:

populate<RABBIT>(10);

关于c++ - 映射 "RABBIT"字符串调用new "RABBIT"(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36612554/

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