Menu
Coddy logo textTech

Adding and Updating Items

Part of the Logic & Flow section of Coddy's C++ journey — lesson 31 of 56.

challenge icon

Challenge

Easy

Extend your inventory tracking system by implementing the functionality to add new items or update the quantities of existing items. This lesson demonstrates how maps automatically handle both new entries and updates to existing ones.

The following inputs will be provided:

  • An integer n representing the number of inventory operations to perform
  • Then n pairs of inputs:
    • A string representing the item name
    • An integer representing the quantity to add

Your program should:

  1. Start with the following initial inventory:
    inventory["apples"] = 50;
    inventory["bananas"] = 30;
    inventory["oranges"] = 25;
  2. Read the number of inventory operations
  3. For each operation, read an item name and quantity
  4. Add the quantity to the item's current stock in the inventory map using the square bracket operator
  5. Print a confirmation message for each operation showing the item name and its new total quantity
  6. After all operations, print the final inventory showing all items and their updated quantities

Use the following exact output format:

For each inventory operation:

Added [quantity] [item_name]. New total: [new_total]

Final inventory:

Final Inventory:
[item1]: [quantity1]
[item2]: [quantity2]
[item3]: [quantity3]
...

The final inventory should be printed in alphabetical order by item name. Use the square bracket operator to add quantities - if the item already exists, it will add to the current quantity; if it's a new item, it will be created with the specified quantity. Remember that inventory[itemName] += quantity will work for both new and existing items because the map automatically initializes new entries with 0.

Try it yourself

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // TODO: Write your code below
    map<string, int> inventory;
    inventory["Laptops"] = 15;
    inventory["Mice"] = 42;
    inventory["Keyboards"] = 28;
    inventory["Monitors"] = 12;
    
    cout << "Initial Inventory Setup:" << endl;
    for (const auto& pair : inventory) {
        cout << pair.first << ": " << pair.second << endl;
    }
    cout << "Inventory system is ready!" << endl;
    
    return 0;
}

All lessons in Logic & Flow