C++ Maps

A C++ map is an STL container that stores key-value pairs. Use std::map when each key should appear only once and you want the keys kept in sorted order.

Think of a map like a small dictionary: you look up a value by its key. For example, a student’s name could be the key, and that student’s score could be the value.

Including the Map Header

To use a map, include the <map> header. A map type is written as std::map<KeyType, ValueType>, where the first type is the key and the second type is the value.

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

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

    scores["Mia"] = 92;
    scores["Alex"] = 88;
    scores["Zoe"] = 95;
    scores["Alex"] = 90;

    for (const auto& entry : scores) {
        std::cout << entry.first << ": " << entry.second << std::endl;
    }

    return 0;
}

Output:

Alex: 90
Mia: 92
Zoe: 95

The expression scores["Alex"] = 90 updates the value for the existing key "Alex". A std::map does not store duplicate keys, so the loop prints one entry for each name. The output is alphabetical because maps sort by key.

Keys and Values

Each map entry contains two parts. The key is stored in entry.first, and the value is stored in entry.second. With std::map<std::string, int>, the key is a std::string and the value is an int.

Keys must be unique. Values do not have to be unique; several different keys can store the same value.

Adding and Updating Entries

The square bracket operator [] is a common way to add or update an entry. If the key already exists, the value is replaced. If the key does not exist, a new entry is created.

You can also use insert() to add an entry only if the key is not already present. This is useful when you do not want to overwrite an existing value by accident.

Finding and Removing Entries

The find() function searches for a key. If it finds the key, it returns an iterator pointing to that entry. If it does not find the key, it returns end(). The erase() function removes an entry by key.

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

int main(void) {
    std::map<std::string, int> inventory = {
        {"apples", 12},
        {"bananas", 8},
        {"oranges", 5}
    };

    inventory.insert({"pears", 6});
    inventory["bananas"] += 2;
    inventory.erase("oranges");

    auto found = inventory.find("bananas");
    if (found != inventory.end()) {
        std::cout << "Bananas: " << found->second << std::endl;
    }

    std::cout << "Has oranges: " << inventory.count("oranges") << std::endl;
    std::cout << "Items:" << std::endl;

    for (const auto& item : inventory) {
        std::cout << item.first << " = " << item.second << std::endl;
    }

    return 0;
}

Output:

Bananas: 10
Has oranges: 0
Items:
apples = 12
bananas = 10
pears = 6

The map starts with three entries. It adds pears, increases the value for bananas, and removes oranges. Since maps are ordered by key, the final loop prints apples, bananas, and pears in sorted order.

Using count()

The count() function returns how many entries match a key. In a std::map, the answer is always 0 or 1, because each key can appear only once.

Use count(key) > 0 when you only need to know whether a key exists. Use find(key) when you need to read or change the found entry through an iterator.

Common Map Functions

Function What it does
map[key] Adds a key with a default value if missing, then returns its value
insert({key, value}) Adds a new pair if the key is not already present
erase(key) Removes the entry with that key
find(key) Returns an iterator to the entry or end()
count(key) Returns 1 if the key exists, otherwise 0
size() Returns the number of key-value pairs

When To Use a Map

Use std::map when you need to associate one value with each unique key and you want to loop through entries in sorted key order. If you do not need sorted keys, the next lesson covers std::unordered_map, which is often chosen for very fast key-based lookup.

Takeaway: std::map stores unique keys, keeps them sorted, and lets you quickly find the value connected to a key.