1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
#include <iostream> #include <vector> #include <string> #include <algorithm> class Item { public: Item(const std::string& name, int quantity) : itemName(name), itemQuantity(quantity) {} std::string getName() const { return itemName; } int getQuantity() const { return itemQuantity; } void setQuantity(int quantity) { itemQuantity = quantity; } void display() const { std::cout << "Item: " << itemName << ", Quantity: " << itemQuantity << "\n"; } private: std::string itemName; int itemQuantity; }; class Inventory { public: void addItem(const Item& item) { auto it = std::find_if(items.begin(), items.end(), [&](const Item& i) { return i.getName() == item.getName(); }); if (it != items.end()) { it->setQuantity(it->getQuantity() + item.getQuantity()); } else { items.push_back(item); } } void removeItem(const std::string& itemName, int quantity) { auto it = std::find_if(items.begin(), items.end(), [&](const Item& i) { return i.getName() == itemName; }); if (it != items.end()) { int newQuantity = it->getQuantity() - quantity; if (newQuantity <= 0) { items.erase(it); } else { it->setQuantity(newQuantity); } } else { std::cout << "Item not found.\n"; } } void displayInventory() const { std::cout << "Inventory:\n"; for (const auto& item : items) { item.display(); } } private: std::vector<Item> items; }; int main() { Inventory inventory; // Add items to inventory inventory.addItem(Item("Sword", 1)); inventory.addItem(Item("Health Potion", 5)); inventory.addItem(Item("Mana Potion", 3)); // Display inventory inventory.displayInventory(); // Remove items from inventory inventory.removeItem("Health Potion", 2); // Display inventory after removal inventory.displayInventory(); return 0; } |
Explanation
- Item Class:
- Represents an individual item with a name and quantity.
- Provides methods to get the name and quantity, set the quantity, and display the item.
- Inventory Class:
- Manages a collection of
Item
objects. - The
addItem()
function adds items to the inventory. If an item already exists, it updates the quantity. - The
removeItem()
function removes or updates the quantity of an item. If the quantity falls to zero or below, the item is removed from the inventory. - The
displayInventory()
function prints all items and their quantities.
- Manages a collection of
- main Function:
- Creates an
Inventory
object. - Adds several items to the inventory.
- Displays the inventory.
- Removes some items from the inventory.
- Displays the updated inventory.
- Creates an