在开关语句相同但对于某些替换变量/向量/等的情况下,如何避免重复代码?



以下代码片段来自我正在研究的库存系统。我不断遇到我跌倒的情况,我应该能够简单地运行一个 for 循环,但在不同的情况下我使用不同的向量/变量/等这一事实让我感到受阻。每当我需要处理在运行时不知道名称的变量或对象时,我都会遇到这个问题。在这种特殊情况下,情况 1: 与情况 2 完全相同:除了在情况 2 中,向量 tankInventory[] 将是 dpsInventory[]:

我觉得我正在做一些从根本上倒退的事情,但我不清楚如何重新定位我对此的思考。有什么建议吗?

case 1:
//loop through the inventory...
for (int i = 0; i < 6; i++)
{
//looking for an empty spot
if (tankInventory[i] == -1)
{
//add the item...
tankInventory[i] = { item };
//decrement the number of items being added
number--;
//and stop the loop if you're out of items to add
if (!number)
break;
}
}
//if there are no more items to add, break;
if (!number)
break;
//but if there are more...
else
{
//switch to main inventory...
character = 0;
//and return to the top
goto returnPoint;
}

使用函数。

只需将公共逻辑提取到函数中,并将任何可以更改的内容作为参数。

此外,您似乎正在使用goto并从switchbreak出来,而不是进行循环。我会做一些类似do {} while (number)while (number) {}的事情,这取决于你需要什么。这样,使用函数就容易多了。

你很可能走在正确的轨道上,这就是我们构建抽象的方式。一个简单的方法是定义一个 lambda:

// you might refine the captures
auto processInventory = [&](auto& inventoryToProcess) {
//loop through the inventory...
for (int i = 0; i < 6; i++)
{
//looking for an empty spot
if (inventoryToProcess[i] == -1)
{
//add the item...
inventoryToProcess[i] = { item };
//decrement the number of items being added
number--;
//and stop the loop if you're out of items to add
if (!number)
break;
}
}
//if there are no more items to add, break;
if (!number)
break;
//but if there are more...
else
{
//switch to main inventory...
character = 0;
//and return to the top
goto returnPoint;
}}
};
switch(condition) {
case 1:
processInventory(tankInventory);
break;
case 2:
processInventory(dpsInventory);
}

最新更新