gpt4 book ai didi

for循环中的c++冗余代码

转载 作者:太空狗 更新时间:2023-10-29 23:43:28 25 4
gpt4 key购买 nike

我有一张用 C++ 编写的 2D map ,代表一个游戏场。在每个字段上都可以有一种交通工具(例如汽车、飞机......(所有这些都是以前在枚举中定义的))。

bool MainClass::isTrue(int x, int y, int w, int h)
{
for (int m = y; m < h; m++)
{
for (int n = x; n < w; n++)
{
if (map_.at(n-1).at(m-1) == SubClass::PartOfEnum::CAR ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::BOAT ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::SHIP ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::PLANE)
return (0);
}
}
return (1);

// other code ..
}

正如某些人所看到的,我正在遍历这张 map 的各个部分,想知道在某些定义的坐标上是否存在其中一种交通工具。问题是 for 循环内的代码对枚举的每个部分重复。所以我的问题是,是否有解决此类问题的方法,只需编写一行代码而不是四行代码。也许将枚举的各个部分保存在一个单独的变量中,然后将这个变量用于循环。 original-enum 还包含一些其他不应属于此循环的对象(在 original-enum 中还有一些其他交通工具,如自行车,但这里只有这四种相关)。提前致谢

最佳答案

So my question is, if there is a solution for this kind of problem to write just one line of code instead of four

您需要四次比较,但您不需要多次访问 map_。一个方便的实用程序应该做的:

bool isVehicle(SubClass::PartOfEnum test) {
return test == SubClass::PartOfEnum::CAR ||
test == SubClass::PartofEnum::BOAT ||
test == SubClass::PartofEnum::SHIP ||
test == SubClass::PartofEnum::PLANE;
}

然后你要测试的是:

for (int n = x; n < w; n++)
{
if (isVehicle(map_.at(n-1).at(m-1)))
return (0);
}

相当直接的重构。除了单一访问之外的其他好处是,人们可以知道条件正在检查什么,而无需深入研究如何检查它的细节。如果需要,现在您可以相当轻松地在多个地方使用相同的条件。更不用说对该函数的任何更新都将应用于您使用它执行检查的所有地方。

关于for循环中的c++冗余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085831/

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