Menu
CoddyTech

检查库存

本课属于 Coddy C++ 学习旅程的“逻辑与流程”单元。第 32 课,共 56 课。

challenge icon

挑战

简单

继续构建你的库存跟踪系统,实现查询特定商品当前库存的功能。本课将演示如何安全地查询 map 中的商品信息,以及如何处理库存中可能不存在的商品。

将提供以下输入:

  • 一个整数 n,表示要执行的库存查询次数
  • 接着是 n 个字符串,表示要查询的商品名称

你的程序应当:

  1. 从以下初始库存开始:
    inventory["apples"] = 50;
    inventory["bananas"] = 30;
    inventory["oranges"] = 25;
    inventory["grapes"] = 40;
  2. 读取库存查询次数
  3. 对于每次查询,读取一个商品名称
  4. 使用 .count() 方法检查库存 map 中是否存在该商品
  5. 如果商品存在,输出当前库存数量
  6. 如果商品不存在,输出一条表示未找到该商品的消息
  7. 完成所有查询后,输出当前库存中不同商品的总数

请使用以下确切的输出格式:

对于每次库存查询:

[item_name]: [quantity] in stock

对于未找到的商品:

[item_name]: Item not found

最后的汇总:

Total items in inventory: [number_of_items]

使用 .count() 方法,在访问每件商品的值之前安全地检查该商品是否存在。如果 inventory.count(itemName) 返回 1,说明该商品存在,你可以安全地访问 inventory[itemName] 来获取其库存数量。如果返回 0,说明该商品不存在。最后汇总时,使用 map 的 .size() 方法获取库存中不同商品的总数。

亲手试试

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // Initialize the inventory with existing items
    map<string, int> inventory;
    inventory["apples"] = 50;
    inventory["bananas"] = 30;
    inventory["oranges"] = 25;
    
    int n;
    cin >> n;
    
    for (int i = 0; i < n; i++) {
        string itemName;
        int quantity;
        cin >> itemName >> quantity;
        
        inventory[itemName] += quantity;
        
        cout << "Added " << quantity << " " << itemName << ". New total: " << inventory[itemName] << endl;
    }
    
    cout << "Final Inventory:" << endl;
    for (const auto& item : inventory) {
        cout << item.first << ": " << item.second << endl;
    }
    
    return 0;
}

逻辑与流程中的所有课

自己练习: C++ 在线编译器