c++ - 重复相同代码的较大函数与较小函数

标签 c++ performance function

我一直在阅读有关保持功能简单且仅用于一个目的的文章。即使是一个进行简单计算并打印出结果的函数也已经太多了。

我一直在为一个小游戏开发一个元素商店系统。商店有游戏中所有可用元素的 vector 。每个 Item 都会跟踪自己的计数(这样不好吗?),如果它的计数为零,则不会出现在库存输出中。

当玩家(骑手)想要购买元素时,商店应检查玩家是否有足够的信用以及该元素是否有库存,然后才将元素从商店中移除(然后添加到玩家的库存中)。

我将所有这些组合到一个函数中,认为这样可以避免重复遍历 Items vector 。

/* ItemShop.cpp
 * non-binary boolean:
 *   returns 0 if item is not in stock
 *   returns 1 if rider has insufficient creds to buy the item
 *   returns 2 if purchase is successful */

int ItemShop::buyItem(const string& itemName, const int cred, Item& newItem) {
    // go through shop inventory and search for item with given name
    for (int i = 0; i < items.size(); i++) {
        if (items[i].getName() == itemName) {
            if (items[i].getCount() > 0) { // item is in stock
                if (items[i].getValue() <= cred) { // rider has enough creds to buy the item
                    newItem = items[i];    // pass a copy of the item by ref
                    newItem.setCount(1);   // take one of that item
                    items[i].removeOne();  // remove one from the shop
                    return 2; // purchase is successful
                }
                return 1; // rider cannot afford to buy the item
            }
        }
    }
    return 0; // item is not in stock
}

在采用这种方法时,我最终得到了一个更大的多功能函数,但我不必多次通过 Item vector 。我想如果我要将函数分解成单独的函数,它们将是:

  1. 检查商品是否有货
  2. 检查玩家是否负担得起
  3. 交易

这些函数中的每一个都必须遍历并找到 vector 中的项目(除非我可能从函数中传递它的引用?)。

总而言之,代码重复越少,我的方法就越合理吗?如果不是,我应该如何分解它?

最佳答案

两条建议:

  1. 将您的元素存放在 std::map<string,Item> 中字符串在哪里 项目名称。这将删除搜索循环。
  2. 使用枚举而不是 int 作为返回值。

您也可以为不同的检查实现简单的功能,但我会说这是一个品味问题。

关于c++ - 重复相同代码的较大函数与较小函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415464/

相关文章:

xml - 让 JAXB 运行得更快

javascript - 未定义的 JavaScript 函数错误

c++ - 创建一个 const char* const* 数组

c++ - 如何错误捕获字符串数组

c++ - 如何在另一个 DLL 的 DLL 上使用 `/DELAYLOAD`

javascript - 如何为选定的控件创建尾随函数?

python - 在 python mysql 中使用 Select 查询作为 if/else block 的参数

c++ - 根据重复次数对输入文本中的单词进行排序?

java - 有什么方法可以进一步优化 Java 反射方法调用?

Java 哈希实用程序