Accessing and Modifying Values
Part of the Logic & Flow section of Coddy's C++ journey — lesson 25 of 56.
Once you have a map with key-value pairs, you'll often need to retrieve or update the values stored in it. The square bracket [] operator provides a convenient way to both access existing values and modify them.
To access a value, simply use the key inside square brackets:
std::map<std::string, int> scores;
scores["Alice"] = 95;
int aliceScore = scores["Alice"]; // Gets 95The same syntax works for updating existing values:
scores["Alice"] = 98; // Updates Alice's score to 98Here's an important behavior to remember: if you use the [] operator with a key that doesn't exist in the map, it automatically creates a new element with that key and initializes it with a default value (0 for integers, empty string for strings, etc.).
int bobScore = scores["Bob"]; // Creates "Bob" with value 0This automatic creation feature makes the [] operator very convenient for both reading and writing map data, as you don't need to check if a key exists before using it.
You can also iterate through all key-value pairs in a map using a range-based for loop. Each element in the map is a pair, where pair.first holds the key and pair.second holds the value:
for (auto pair : scores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}This will print every key-value pair stored in the map, one per line.
Challenge
EasyCreate a program that manages a product inventory system using a std::map. Your program will track product names and their current stock quantities, allowing you to access and update inventory levels.
The following inputs will be provided:
- An integer
nrepresenting the number of initial products - Then
npairs of inputs:- A string representing the product name
- An integer representing the initial stock quantity
- A string representing a product name to update
- An integer representing the new stock quantity for that product
Your program should:
- Create a
std::map<std::string, int>namedinventory - Read the number of initial products
- For each product, read the name and stock quantity, then add them to the map using the square bracket notation
- Print the initial inventory in the format shown below
- Read the product name and new quantity to update
- Use the square bracket operator to update the stock quantity for the specified product
- Print the updated inventory showing the modified stock level
Use the following exact output format:
Initial Inventory:
[product1]: [quantity1]
[product2]: [quantity2]
[product3]: [quantity3]
...
Updated Inventory:
[product1]: [quantity1]
[product2]: [updated_quantity2]
[product3]: [quantity3]
...The products should be printed in the order they appear when iterating through the map (alphabetical order by product name). Use a range-based for loop to iterate through the map both times, accessing each key-value pair with pair.first for the product name and pair.second for the quantity. If the product name to update doesn't exist in the map, the square bracket operator will automatically create a new entry with that name and the specified quantity.
Cheat sheet
Use the square bracket [] operator to access and modify map values:
std::map<std::string, int> scores;
scores["Alice"] = 95; // Set value
int aliceScore = scores["Alice"]; // Get value
scores["Alice"] = 98; // Update valueIf you use [] with a key that doesn't exist, it automatically creates a new element with a default value:
int bobScore = scores["Bob"]; // Creates "Bob" with value 0Use a range-based for loop to iterate through all key-value pairs. Each pair has .first for the key and .second for the value:
for (auto pair : scores) {
// pair.first = key (e.g. "Alice")
// pair.second = value (e.g. 98)
}Try it yourself
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Read the number of initial products
int n;
cin >> n;
// Create the inventory map
map<string, int> inventory;
// Read initial products and quantities
for (int i = 0; i < n; i++) {
string product;
int quantity;
cin >> product >> quantity;
// TODO: Add the product to the inventory map
}
// TODO: Print the initial inventory
// Read product to update and new quantity
string updateProduct;
int newQuantity;
cin >> updateProduct >> newQuantity;
// TODO: Update the product quantity in the map
// TODO: Print the updated inventory
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency2Vectors (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