Skip to content
Exercise · Final Project · lesson 3 of 3

Exercise: generic warehouse

Write the class template template <typename Item> class Inventory, a warehouse that counts the units of each item. Keep the quantities in a std::map<Item, int>; add the fields yourself.

void add(const Item& item, int qty) puts qty units of item into the warehouse. bool take(const Item& item, int qty) takes qty units of item out of the warehouse and returns true. int count(const Item& item) const returns how many units of the item the warehouse holds.

  • after add("apple", 5) and add("apple", 3): count("apple") → 8
  • when count("pear") is 2: take("pear", 3) → false, and count("pear") stays 2
  • for an item that was never added: count("kiwi") → 0

Constraints: qty is positive, and the tests use std::string and int as Item. If there are fewer units than qty, take returns false and changes nothing, and count returns 0 for an unknown item.

Do not add extra #include lines unless the task says so explicitly.

inventory.cpp — cpp
cpp · 17 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way