Adding and Updating Items
Part of the Logic & Flow section of Coddy's C++ journey — lesson 31 of 56.
Challenge
EasyExtend 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
nrepresenting the number of inventory operations to perform - Then
npairs of inputs:- A string representing the item name
- An integer representing the quantity to add
Your program should:
- Start with the following initial inventory:
inventory["apples"] = 50;
inventory["bananas"] = 30;
inventory["oranges"] = 25; - Read the number of inventory operations
- For each operation, read an item name and quantity
- Add the quantity to the item's current stock in the inventory map using the square bracket operator
- Print a confirmation message for each operation showing the item name and its new total quantity
- 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
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items