C++ 实现咖啡店鲜牛奶库存管理:操作记录处理与盘点揭秘
以下是用 C++ 实现的代码示例: ```cpp #include <iostream> #include <vector> struct Milk { int brand; int quantity; int expirationDay; }; class CoffeeShop { private: std::vector<Milk> stocks; void updateExpiration() { for (auto& milk : stocks) { if (milk.expirationDay > 0) { milk.expirationDay--; } } } void consume(int quantity) { int totalConsumed = 0; for (auto it = stocks.begin(); it!= stocks.end();) { if (it->expirationDay > 0 && totalConsumed < quantity) { if (it->quantity <= quantity - totalConsumed) { totalConsumed += it->quantity; it = stocks.erase(it); } else { it->quantity -= quantity - totalConsumed; totalConsumed = quantity; } } else { it++; } } } public: void purchase(int brandAQuantity, int brandBQuantity) { Milk brandA = {1, brandAQuantity, 7}; Milk brandB = {2, brandBQuantity, 15}; stocks.push_back(brandA); stocks.push_back(brandB); } void check() { int brandAStock = 0; for (const auto& milk : stocks) { if (milk.brand == 1) { brandAStock += milk.quantity; } } std::cout << "A 品牌牛奶的库存量: " << brandAStock << std::endl; } void handleOperations() { int n; std::cin >> n; for (int i = 0; i < n; i++) { int operation; std::cin >> operation; if (operation == 1) { int brandAQuantity, brandBQuantity; std::cin >> brandAQuantity >> brandBQuantity; purchase(brandAQuantity, brandBQuantity); } else if (operation == 2) { int consumption; std::cin >> consumption; consume(consumption); } else if (operation == 3) { check(); } updateExpiration(); } } }; int main() { CoffeeShop shop; shop.handleOperations(); return 0; } ``` 以下是 3 个改进建议: 1. 可以添加错误处理机制,比如输入不符合格式时的处理。 2. 可以将一些功能封装成单独的函数,以提高代码的可读性和可维护性。 3. 考虑使用更高效的数据结构来存储库存信息,例如优先队列。 ######[AI写代码神器 | 663点数解答 | 2024-12-29 17:06:34]
- Python实现Q老师成绩管理任务:修改与查看学生成绩(字节豆包 | 191点数解答 | 2025-12-20 20:55:41)66
- Python 代码助力 Q 老师高效管理班级学生成绩:修改与查看一键搞定(字节豆包 | 326点数解答 | 2025-12-27 20:48:12)66
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)338
- 卡牌游戏技能“教化”机制全解析:规则、代码与注意要点 (DeepSeek | 353点数解答 | 2025-07-07 15:40:28)166
- Python 模拟无名杀“教化”技能:出牌阶段规则与代码实现及优化建议(字节豆包 | 546点数解答 | 2025-07-07 15:41:02)169
- Java 实现“教化”技能:出牌阶段限两次的牌获取规则代码解析(字节豆包 | 1003点数解答 | 2025-07-07 15:41:54)142
- JavaScript 实现“教化”技能:两次出牌限制与牌型记录逻辑揭秘(字节豆包 | 846点数解答 | 2025-07-07 15:42:46)180
- 工程师必备!10 种工程日常易用管理工具大揭秘(百度文心 | 346点数解答 | 2023-11-09 18:26:09)288
- CentOS下Java进程出现futex_wait_queue_me问题的处理全流程(阿里通义 | 283点数解答 | 2023-11-20 14:51:26)453
- bookmanage 数据库表创建、测试数据添加及多需求 SQL 操作全解析(GPT | 909点数解答 | 2024-06-22 22:25:19)406
- WinForm实现图书管理系统:数据库操作、界面设计与功能全解析(GPT | 1163点数解答 | 2024-06-22 22:26:42)362
- 替雷利珠单抗致免疫相关性糖尿病:病例报道与机制探讨,为临床用药敲响警钟( | 164点数解答 | 2024-10-11 14:52:52)261