Menu
Coddy logo textTech

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 95

The same syntax works for updating existing values:

scores["Alice"] = 98; // Updates Alice's score to 98

Here'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 0

This 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 icon

Challenge

Easy

Create 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 n representing the number of initial products
  • Then n pairs 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:

  1. Create a std::map<std::string, int> named inventory
  2. Read the number of initial products
  3. For each product, read the name and stock quantity, then add them to the map using the square bracket notation
  4. Print the initial inventory in the format shown below
  5. Read the product name and new quantity to update
  6. Use the square bracket operator to update the stock quantity for the specified product
  7. 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 value

If 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 0

Use 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow