Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a coat check at a theater. When you hand over your jacket, the attendant gives you a numbered ticket. That ticket is your "key." You don't care where the jacket is physically stored in the back room; you just know that when you present ticket #42, you get exactly one specific coat back. This is the essence of a map: associating a unique key with a specific value.

Now, imagine a slightly different scenario: a "Group Check." You're with four friends, and the attendant gives you one single ticket for the whole group. When you hand back that one ticket, the attendant brings out four different coats. That's a multimap. The key is the same, but it's linked to multiple values.

Mapping the Analogy to C++

  • The Ticket (The Key): In C++, this is the first type you define in the template, e.g., std::map<int, std::string>. The int is the ticket.
  • The Coat (The Value): This is the second type. In the example above, the std::string represents the coat.
  • The Retrieval: Just like handing over a ticket, using the key allows you to jump straight to the value without searching through every single item in the collection.
  • The Group Ticket (Multimap): std::multimap allows the same key to be used multiple times, meaning one "ticket" can point to a whole bunch of "coats."

Handling Unique Pairs with std::map

I've seen a lot of developers use vectors for everything, but that becomes a nightmare when you need to look things up by a name or an ID. Let's look at a real scenario: a game character's attribute system. Instead of making ten different variables for strength, agility, and luck, we can use a map.

#include <iostream>
#include <map>
#include <string>

int main() {
    // Mapping attribute names to their current values
    std::map<std::string, int> stats;

    stats["Strength"] = 18;
    stats["Agility"] = 12;
    stats["Intelligence"] = 15;

    // Updating a value is just as easy as setting it
    stats["Strength"] = 19; 

    std::cout < "Current Strength: " < stats["Strength"] < std::endl;
    return 0;
}

One thing you need to watch out for: the [] operator is convenient, but it's "aggressive." If you try to access a key that doesn't exist using stats["Luck"], C++ won't throw an error. Instead, it will silently create that key and give it a default value (like 0 for an int). If you just want to check if something exists without accidentally creating it, use stats.find("Luck").

When One Key Isn't Enough: std::multimap

A standard std::map will overwrite the old value if you try to insert a duplicate key. But what if you're building a dictionary or a phonebook where one person might have three different phone numbers? That's where std::multimap comes in.

Keep in mind that because std::multimap allows duplicate keys, you can't use the [] operator. The compiler wouldn't know which of the multiple values you're trying to access. Instead, you use insert and equal_range.

#include <iostream>
#include <map>
#include <string>

int main() {
    std::multimap<std::string, std::string> phonebook;

    phonebook.insert({"Alice", "555-0101"});
    phonebook.insert({"Alice", "555-0102"}); // Alice has a second number
    phonebook.insert({"Bob", "555-0201"});

    // To find all numbers for Alice, we get a range
    auto range = phonebook.equal_range("Alice");

    std::cout < "Alice's numbers: " < std::endl;
    for (auto it = range.first; it != range.second; ++it) {
        std::cout < it->second < std::endl;
    }

    return 0;
}

I should mention that both of these containers are typically implemented as Red-Black Trees. This means they keep your keys sorted automatically. If you iterate through a map, you'll see the keys in alphabetical or numerical order. If you don't need that sorting and want even more speed, you'd look at unordered_map, but for now, stick with these basics.




📋 Practical Task

Build a Course Enrollment Registry

You need to create a small system that tracks which students are enrolled in which courses. Since one course can have many students, a std::multimap is the perfect tool for this.

Requirements:

  • Create a std::multimap<std::string, std::string> where the key is the Course Name (e.g., "CS101") and the value is the Student Name.
  • Insert at least five entries. Ensure at least two different students are enrolled in the same course.
  • Write a function or a block of code that takes a course name as input and prints out every student enrolled in that specific course.
  • If the course is not found, print a message saying "No students enrolled in this course."
Rating
0 0

There are no comments for now.

to be the first to leave a comment.