Write an Inventory class holding Item objects with add (merging existing items), remove with stock checks, total value, and a list of items low on stock.
Solution
main.cpp
#include <iostream>
#include <string>
#include <vector>
class Inventory {
struct Item { std::string name; int qty; double price; };
std::vector<Item> items_;
Item* find(const std::string& n) {
for (auto& it : items_) if (it.name == n) return ⁢
return nullptr;
}
public:
void add(const std::string& n, int qty, double price) {
if (Item* it = find(n)) it->qty += qty;
else items_.push_back({n, qty, price});
}
bool remove(const std::string& n, int qty) {
Item* it = find(n);
if (!it || it->qty < qty) return false;
it->qty -= qty;
return true;
}
double value() const {
double v = 0;
for (const auto& it : items_) v += it.qty * it.price;
return v;
}
void low_stock(int limit) const {
for (const auto& it : items_) if (it.qty < limit) std::cout << it.name << '(' << it.qty << ") ";
std::cout << '\n';
}
};
int main() {
Inventory inv;
inv.add("mouse", 10, 450);
inv.add("keyboard", 4, 1200);
inv.add("mouse", 5, 450);
std::cout << inv.remove("keyboard", 3) << inv.remove("keyboard", 3) << inv.remove("webcam", 1) << '\n';
std::cout << "value " << inv.value() << '\n';
inv.low_stock(5);
return 0;
}
Output Verified by compiling and running
100
value 7950
keyboard(1)
The nested Item type and the find helper are private details; users only see inventory operations. Adding an existing name merges the quantity instead of duplicating the item.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!