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 them out and returns true. int count(const Item& item) const returns how many units of the item the warehouse holds.
- after
add("apple", 5)andadd("apple", 3):count("apple")→8 - when
count("pear")is2:take("pear", 3)→false, andcount("pear")stays2 - 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.