Maps

A map is a container in C++ which stores pairs of items like this:

key -> value

and keeps them sorted by key automatically.

Example:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> ages;

    ages["Alice"] = 25;
    ages["Bob"] = 30;
    ages["Charlie"] = 22;

    for (auto p : ages)
        cout << p.first << ": " << p.second << endl;
}

Output:

Alice: 25
Bob: 30
Charlie: 22

Notice that the names are printed in alphabetical order — because a map sorts keys automatically.

Creating a map

To use a map, include:

#include <map>

Then you can declare it like this:

map<int, string> students;     // key: int, value: string
map<string, double> prices;    // key: string, value: double
map<char, int> frequency;      // key: char, value: int

Adding and accessing elements

map<string, int> scores;

scores["Mark"] = 90;          // add using [] 

cout << scores["Mark"];       // prints 90

If you access a key that doesn’t exist with [], it will create it with a default value (like 0).

cout << scores["Unknown"];  // creates "Unknown" with value 0

If you don’t want that behavior, use count() to check first if it exists.

if (scores.count("Tom"))
    cout << "Tom found!";

Common operations

Operation Example Description
m[key] m["Bob"] Access or create element
erase(key) m.erase("Bob") Removes key and value
count(key) if (m.count("Bob")) 1 if key exists, 0 if not
size() m.size(); Returns number of elements
clear() m.clear(); Deletes all elements
empty() m.empty(); Checks if map is empty

Example: word frequency counter

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    string text = "apple banana apple orange banana apple";
    map<string, int> freq;

    string word;
    for (auto c : text) {
        if (c == ' ') {
            if (!word.empty()) freq[word]++;
            word.clear();
        } else {
            word += c;
        }
    }
    if (!word.empty()) freq[word]++; // last word

    for (auto p : freq)
        cout << p.first << ": " << p.second << endl;
}

Output:

apple: 3
banana: 2
orange: 1

Iterating through a map

You can loop through it with a range-based for:

for (auto p : myMap)
    cout << p.first << " -> " << p.second << endl;

or using iterators:

for (auto it = myMap.begin(); it != myMap.end(); it++)
    cout << it->first << ": " << it->second << endl;

first = key, second = value.

Kinds of maps

Type Keeps order? Allows duplicate keys? Speed (average) Notes
map Yes No O(log n) Stores keys sorted (balanced tree)
unordered_map No No O(1) average Fast, but order is random

Example: unordered_map

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
    unordered_map<string, int> age;

    age["Bob"] = 30;
    age["Alice"] = 25;
    age["Tom"] = 28;

    for (auto p : age)
        cout << p.first << ": " << p.second << endl;
}

Output:

(order may be random)
Bob: 30
Tom: 28
Alice: 25

So unordered_map is usually faster, but doesn’t sort keys.