0
0
CppConceptBeginner · 3 min read

What is map in C++: Explanation and Example

In C++, map is a container from the Standard Template Library (STL) that stores key-value pairs in sorted order by keys. It allows fast lookup, insertion, and deletion of elements using keys, similar to a real-life dictionary where you look up a word to find its meaning.
⚙️

How It Works

A map in C++ works like a real-world dictionary. Imagine you have a book where each word (key) is linked to its meaning (value). When you want to find the meaning of a word, you look it up quickly because the words are sorted alphabetically. Similarly, a map stores pairs of keys and values, and it keeps the keys sorted automatically.

Under the hood, map uses a balanced tree structure to keep keys in order. This means when you add or find a key, the map can do it quickly without searching every item. This is like having a well-organized dictionary where you can jump directly to the word you want.

💻

Example

This example shows how to create a map that links names to ages, add some entries, and print them in sorted order by name.

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

int main() {
    std::map<std::string, int> ageMap;

    // Add some key-value pairs
    ageMap["Alice"] = 30;
    ageMap["Bob"] = 25;
    ageMap["Charlie"] = 35;

    // Print all entries
    for (const auto& pair : ageMap) {
        std::cout << pair.first << " is " << pair.second << " years old.\n";
    }

    return 0;
}
Output
Alice is 30 years old. Bob is 25 years old. Charlie is 35 years old.
🎯

When to Use

Use a map when you need to store data as pairs where each key is unique and you want to quickly find, add, or remove items by key. For example, you can use a map to store phone numbers by contact name, product prices by product ID, or student grades by student ID.

Maps are especially useful when the order of keys matters or when you want automatic sorting. If you don't need sorting and want faster access, unordered_map might be better.

Key Points

  • Map stores key-value pairs with unique keys.
  • Keys are automatically sorted in ascending order.
  • Fast lookup, insertion, and deletion by key.
  • Useful for dictionary-like data storage.
  • Implemented as a balanced tree internally.

Key Takeaways

A map stores unique keys with associated values in sorted order.
It allows fast searching, adding, and removing by key.
Use map when you need ordered key-value pairs like a dictionary.
Maps keep keys sorted automatically using a balanced tree.
For unordered access, consider unordered_map instead.