LearnFrenzy
Sign in Take a free test

Classes and Objects · Class Programs · Question 5

Inventory class managing a vector of items in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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 &it;
        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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links