fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Define the inventory class
  5. class Inventory {
  6. private:
  7. unordered_map<string, int> items; // Hash table to store items and their quantities
  8. int total_inventory; // Total inventory count
  9.  
  10. public:
  11. // Constructor
  12. Inventory() {
  13. total_inventory = 0;
  14. }
  15.  
  16. // Add an item to the inventory
  17. void add_item(string item_name, int quantity) {
  18. if (items.find(item_name) == items.end()) {
  19. // If the item doesn't exist in the inventory, add it
  20. items[item_name] = quantity;
  21. total_inventory += quantity;
  22. } else {
  23. // If the item already exists, update its quantity
  24. int old_quantity = items[item_name];
  25. items[item_name] = old_quantity + quantity;
  26. total_inventory += quantity;
  27. }
  28. }
  29.  
  30. // Remove an item from the inventory
  31. void remove_item(string item_name, int quantity) {
  32. if (items.find(item_name) != items.end()) {
  33. // If the item exists in the inventory, update its quantity
  34. int old_quantity = items[item_name];
  35. if (old_quantity > quantity) {
  36. items[item_name] -= quantity;
  37. total_inventory -= quantity;
  38. } else {
  39. // If the quantity to remove is greater than the current quantity, remove the item completely
  40. items.erase(item_name);
  41. total_inventory -= old_quantity;
  42. }
  43. }
  44. }
  45.  
  46. // Check the quantity of a specific item in the inventory
  47. int check_quantity(string item_name) {
  48. if (items.find(item_name) != items.end()) {
  49. // If the item exists in the inventory, return its quantity
  50. return items[item_name];
  51. } else {
  52. // If the item doesn't exist in the inventory, return 0
  53. return 0;
  54. }
  55. }
  56.  
  57. // Display the total inventory count
  58. int get_total_inventory() {
  59. return total_inventory;
  60. }
  61. };
  62.  
  63. int main() {
  64. Inventory site_inventory;
  65.  
  66. // Add items to the inventory
  67. site_inventory.add_item("T-shirt", 100);
  68. site_inventory.add_item("Shoes", 50);
  69. site_inventory.add_item("Book", 30);
  70.  
  71. // Remove items from the inventory
  72. site_inventory.remove_item("T-shirt", 30);
  73. site_inventory.remove_item("Book", 15);
  74.  
  75. // Check the quantity of specific items
  76. cout << "Quantity of T-shirt: " << site_inventory.check_quantity("T-shirt") << endl;
  77. cout << "Quantity of Shoes: " << site_inventory.check_quantity("Shoes") << endl;
  78. cout << "Quantity of Book: " << site_inventory.check_quantity("Book") << endl;
  79.  
  80. // Display the total inventory count
  81. cout << "Total inventory: " << site_inventory.get_total_inventory() << endl;
  82.  
  83. return 0;
  84. }
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Quantity of T-shirt: 70
Quantity of Shoes: 50
Quantity of Book: 15
Total inventory: 135